rails has_many and access inside of class - ruby-on-rails

I have a rails model class
class Model < ActiveRecord::Base
has_many :object_collection
def add_object(object)
object_collection.push object // works
#object_collection.push object // does not work
self.object_collection.push object // works
end
end
I was wondering if someone can please explain to me why the # does not work yet self does i thought these two meant the same
cheers

They are not the same. Consider the following Ruby code:
class Person
attr_accessor :employer
end
john = Person.new
john.employer = "ACME"
john.employer # equals "ACME"
The method attr_accessor conveniently generates an attribute reader and writer for you (employer= and employer). You can use these methods to read and write an attribute, which is stored in the instance variable #employer.
Now, we can rewrite the above to the following, which is functionally identical to the code above:
class Person
def employer=(new_employer)
#works_for = new_employer
end
def employer
#works_for
end
end
john = Person.new
john.employer = "ACME"
john.employer # equals "ACME"
Now, the instance variable #employer is no longer used. We chose to write the accessors manually, and have the freedom to pick a different name for the instance variable. In this particular example, the name of the instance variable is different than the name of the attribute accessors. There is nothing that prevents you from doing that.
This is similar to how ActiveRecord stores its attributes internally. They are not stored in instance variables of the same name, that is why your push call to #object_collection does not work.
As you may understand, attribute readers and writers offer a certain abstraction that can hide the implementation details from you. Reading and writing instance variables directly in subclasses is therefore generally considered bad practice.

#foo identifies an instance variable called #foo. foo identified a method called foo.
By default, instance variables in Ruby are private. It means you cannot access the value of an instance variable unless you have some public method that exposes the value.
Those methods are called setters and getters. By convenction, setter and getter have the same name of the instance variable, but this is not a requirement.
class MyClass
def initialize
#foo
end
def foo=(value)
#foo = foo
end
def foo
#foo
end
def an_other_foo=(value)
#foo = foo
end
def an_other_foo
#foo
end
end
Though methods and instance variables can have similar names, thery are different elements.
If this topic is not clear to you, you probably need to stop playing with Rails and go back studying how Ruby works.
In your specific case, object_collection doesn't exist as an instance variable because it's an association method.

They do not mean the same thing. One is an instance variable, the other is a method.
The #foo means "the value of the instance variable foo", where as self.foo means "the value of a call to the method foo on myself".
It is typical for a method foo= to set the #foo instance variable, so I can see how someone new to the language might be confused. I'd encourage you to pick up a book on the ruby language. There's one specifically for people who have done some rails but never learned ruby proper. You often can hack rails without understanding the language or what these statements mean, but you'll be far less productive than someone who spends the small amount of time it takes to learn the ruby language itself.
As a general rule, use the self.foo form whenever you can, as this is less sensitive to changes in the classes definition.

Related

Rails ActiveAttr Gem, manipulation of attributes within Class?

I have a Rails 5 class which includes ActiveAttr::Model, ActiveAttr:MassAssignment and ActiveAttr::AttributeDefaults.
It defines a couple of attributes using the method attribute and has some instance methods. I have some trouble manipulating the defined attributes. My problem is how to set an attribute value within the initializer. Some code:
class CompanyPresenter
include ActiveAttr::Model
include ActiveAttr::MassAssignment
include ActiveAttr::AttributeDefaults
attribute :identifier
# ...
attribute :street_address
attribute :postal_code
attribute :city
attribute :country
# ...
attribute :logo
attribute :schema_org_identifier
attribute :productontology
attribute :website
def initialize(attributes = nil, options = {})
super
fetch_po_field
end
def fetch_po_field
productontology = g_i_f_n('ontology') if identifier
end
def uri
#uri ||= URI.parse(website)
end
# ...
end
As I have written it, the method fetch_po_field does not work, it thinks that productontology is a local variable (g_i_f_n(...) is defined farther down, it works and its return value is correct). The only way I have found to set this variable is to write self.productontology instead. Moreover, the instance variable #uri is not defined as an attribute, instead it is written down only in this place and visible from outside.
Probably I have simply forgotten the basics of Ruby and Rails, I've done this for so long with ActiveRecord and ActiveModel. Can anybody explain why I need to write self.productontology, using #productontology doesn't work, and why my predecessor who wrote the original code mixed the # notation in #uri with the attribute-declaration style? I suppose he must have had some reason to do it like this.
I am also happy with any pointers to documentation. I haven't been able to find docs for ActiveAttr showing manipulation of instance variables in methods of an ActiveAttr class.
Thank you :-)
To start you most likely don't need the ActiveAttr gem as it really just replicates APIs that are already available in Rails 5.
See https://api.rubyonrails.org/classes/ActiveModel.html.
As I have written it, the method fetch_po_field does not work, it thinks that productontology is a local variable.
This is really just a Ruby thing and has nothing to do with the Rails Attributes API or the ActiveAttr gem.
When using assignment you must explicitly set the recipient unless you want to set a local variable. This line:
self.productontology = g_i_f_n('ontology') if identifier
Is actually calling the setter method productontology= on self using the rval as the argument.
Can anybody explain why I need to write self.productontology, using
#productontology doesn't work
Consider this plain old ruby example:
class Thing
def initialize(**attrs)
#storage = attrs
end
def foo
#storage[:foo]
end
def foo=(value)
#storage[:foo] = value
end
end
irb(main):020:0> Thing.new(foo: "bar").foo
=> "bar"
irb(main):021:0> Thing.new(foo: "bar").instance_variable_get("#foo")
=> nil
This looks quite a bit different then the standard accessors you create with attr_accessor. Instead of storing the "attributes" in one instance variable per attribute we use a hash as the internal storage and create accessors to expose the stored values.
The Rails attributes API does the exact same thing except its not just a simple hash and the accessors are defined with metaprogramming. Why? Because Ruby does not let you track changes to simple instance variables. If you set #foo = "bar" there is no way the model can track the changes to the attribute or do stuff like type casting.
When you use attribute :identifier you're writing both the setter and getter instance methods as well as some metadata about the attribute like its "type", defaults etc. which are stored in the class.

Setting an attribute in a rails concern [duplicate]

In testing a getter/setter pair in a rails model, I've found a good example of behavior I've always thought was odd and inconsistent.
In this example I'm dealing with class Folder < ActiveRecord::Base.
Folder belongs_to :parent, :class_name => 'Folder'
On the getter method, if I use:
def parent_name
parent.name
end
...or...
def parent_name
self.parent.name
end
...the result is exactly the same, I get the name of the parent folder. However, in the getter method if I use...
def parent_name=(name)
parent = self.class.find_by_name(name)
end
... parent becomes nil, but if I use...
def parent_name=(name)
self.parent = self.class.find_by_name(name)
end
...then then it works.
So, my question is, why do you need to declare self.method sometimes and why can you just use a local variable?
It seems the need for / use of self in ActiveRecord is inconsistent, and I'd like to understand this better so I don't feel like I'm always guessing whether I need to declare self or not. When should you / should you not use self in ActiveRecord models?
This is because attributes/associations are actually methods(getters/setters) and not local variables. When you state "parent = value" Ruby assumes you want to assign the value to the local variable parent.
Somewhere up the stack there's a setter method "def parent=" and to call that you must use "self.parent = " to tell ruby that you actually want to call a setter and not just set a local variable.
When it comes to getters Ruby looks to see if there's a local variable first and if can't find it then it tries to find a method with the same name which is why your getter method works without "self".
In other words it's not the fault of Rails, but it's how Ruby works inherently.

Ruby/Rails: Understanding ruby getter-setter methods and instances

I am new to ruby and programming in general and am trying to grasp a few key concepts.
Given I have a class Dog, with the below characteristics.
class Dog
attr_accessor :type, :popularity, :total
def initialize(type = nil)
#type = type
end
def total_dogs
Dog.count
end
def total
Dog.where(:type => self.type).size
end
def popularity
total.to_f/total_dogs
end
end
What I am trying to understand, is how ruby persists attributes to an instance via getter/setter methods. Its clear to me that if I instantiate a new instance and then save attributes to that instance, those attributes are tied to that instance because if I look at the object the attributes appear as such:
#dog = Dog.new
#dog
=> #<Dog:0x007fa8689ea238 #type=nil>
Its easy for me to understand that as I pass the #dog object around its always going to have the #type attribute as nil.
However, the situation I am having trouble understanding is if I pass this #dog object to another class. Like if I did:
Owner.new(#dog)
When I am in the owner class and I call #dog.popularity how does it know the value of popularity for that instance? At runtime are all methods processed and then that instance just always is tied to the value at the time? Apologies if this makes no sense or I am way off.
When you do
#dog = Dog.new
You do two spearate things
1) Create an instance variable #dog for whatever object your code is currently inside
2) Instantiate a new instance of Dog (with all its methods and attributes) and assign a reference to it to #dog
#dog is a variable, that just happens to point at the Dog instance ("instance of class" generally same meaning as "object") you created at that point. You can set other variables to point to the same instance, and in Ruby this is generally how you pass data around. Objects contain instance variables, and those instance variables point to yet more objects.
Using the assignment operator (i.e "=") you can point a variable at any other object.
To answer your questions in turn:
When I am in the owner class and I call #dog.popularity how does it
know the value of popularity for that instance?
You have to be careful in Ruby (and OO languages in general) to differentiate between class and object in your descriptions and questions. Ruby I'm assuming you are referring to a line of code in the Owner class, and that you intend it to work with an owner object. I'd also assume that #dog is an attribute you have added to Owner.
In which case, Ruby knows because #dog points to the Dog object that you added to owner. Each Dog object has its own copy of all of Dog's instance variables. You do need to take care in Ruby though, because variables point to objects, that you aren't simply passing in the same Dog object to all the owners (i.e. they all effectively share a single dog). So you need to understand when you are creating new instances (via new) and when you are simply handling existing references.
At runtime are all methods processed and then that instance just
always is tied to the value at the time?
No. At runtime, basic Ruby will only perform the assignments that you have coded. Instance variables may not even exist until the code that assigns them has been run. If you use attr_reader etc methods, then the variables will at least exist (but will be nil unless you assign something during initialize)
Niel has a great answer for this, I just want to add something to it.
Counting Dogs :)
You need a class variable to do this..
class Dog
##count = 0 # this is a class variable; all objects created by this class share it
def initialize
##count += 1 # when we create a new Dog, we increment the count
end
def total
##count
end
end
There is another way to do this with "instance variables of the Class object" but that's a bit of an advanced topic.
Accessing Instance Variables
In Ruby, variables are really just references to objects / instances.
> x = 1
=> 1
> x.class
=> Fixnum
> 1.instance_variables
=> []
x is a reference to the object '1', which is an instance of class Fixnum.
The '1' object is an instance of Fixnum which does not contain any instance variables.
It is not different in any way from a reference to a new "Dog" instance.
Similarly, you can say x = Dog.new , then x is a reference to an instance of class Dog.
class Dog
attr_accessor :legs # this defines the 'legs' and 'legs=' methods!
end
x = Dog.new
x.instance_variables
=> [] # if you would assign legs=4 during "initialize", then it would show up here
x.legs = 4 # this is really a method call(!) to the 'legs' method
x.instance_variables # get created when they are first assigned a value
=> [:legs]
It does not matter if you pass such a reference to a method call, or to another class or just evaluate it by itself - Ruby knows it's an object reference, and looks inside the object and it's inheritance chain on how to resolve things.
Resolving Method Names
That was only the partial truth :) When interpreting x.legs , Ruby checks if there is a method in the class-inheritance chain of the object, which responds to that name 'legs'.
It is not magically accessing the instance variable with the same name!
We can define a method 'legs' by doing "attr_reader :legs" or "attr_accessor :legs", or by defining the method ourselves.
class Dog
def legs
4 # most dogs have 4 legs, we don't need a variable for that
end
end
x.legs # this is a method call! it is not directly accessing a :legs instance variable!
=> 4
x.instance_variables
=> [] # there is no instance variable with name ":legs"
and if we try to implement it as a method and an instance variable, this happens: :)
class Dog
attr_accessor :legs # this creates "def legs" and "def legs=" methods behind the scenes
def legs # here we explicitly override the "def legs" method from the line above.
4
end
end
x = Dog.new
x.legs # that's the method call we implemented explicitly
=> 4
x.legs = 3 # we can still assign something to the instance_variable via legs=
=> 3
x.legs # the last definition of a method overrides previous definitions
# e.g. it overrides the automatically generated "legs" method
=> 4
attr_accessor :legs is just a short hand notation for doing this:
class Dog
def legs
#legs
end
def legs=(value)
#legs = value
end
end
there is no magic way instance variable get automatically accessed. They are always accessed through a method, which can be overridden later.
I hope that makes sense to you
When you create an object, you don't need to use the # symbol. The variable is the object. So if you have multiple dogs, you'd do:
myDog = Dog.new(brown)
yourDog = Dog.new(white)
From there, you can say:
yourDog.type #white
myDog.type #brown
What you would NOT do is:
#dog = Dog.new #myDog
#dog = Dog.new #yourDog
If you need multiple versions of an object, you just give them different names. So if you create multiple dogs and pass them to other objects, they will work. For example:
Say your owner class is:
Class Owner
def initialize(pet)
puts "my pet is #{pet.type}"
end
Then using the instance variable would be:
me = Owner.new(myDog) #my pet is brown
you = Owner.new(yourDog) #my pet is white
Both "type" and "popularity" are methods on "dog" instances. Their definition is as follows:
class Dog
# getter
def type
#type
end
def popularity
total.to_f/total_dogs
end
end
This is roughly equivalent to:
class Dog
attr_accessor :type
def popularity
total.to_f/total_dogs
end
end
Note that attr_accessor is just a shortcut for defining a getter method. If you define a method yourself it is pointless to use attr_accessor:
class Dog
attr_accessor :popularity
# this will override getter defined by attr_accessor
def popularity
total.to_f/total_dogs
end
end
Back to your question: #dog.type invokes type method on #dog which returns its instance variable; #dog.popularity invokes popularity method on #dog which does calculations (as defined by you) on the fly and returns the result. No magic here!

Rails AntiPatterns book - Doubts on composition

I'm reading the Rails AntiPatterns book, which I'm enjoying a lot. At one point, the author talks about the goodness of composition and it gives an example where an Order class gives the responsibility of conversion (to other formats) to another class, called OrderConverter. The classes are defined as:
class Order < ActiveRecord::Base
def converter
OrderConverter.new(self)
end
end
class OrderConverter
attr_reader :order
def initialize(order)
#order = order
end
def to_xml
# ...
end
def to_json
# ...
end
...
end
And then the author says: "In this way, you give the conversion methods their own home, inside a separate and easily testable class. Exporting the PDF version of an order is now just a matter of call-ing the following:"
#order.converter.to_pdf
Regarding to this, my questions are:
Why do you think that order object is preceded by an #? Shouldn't it be created as:
order = Order.new
And then convert by doing:
order.converter.to_pdf
Why is the attr_reader :order line needed in the OrderConverter? It's so we can access the order from an OrderConverter object? Is it needed to be able to do
order.converter.to_pdf ? We could do that without that attr_reader right?
An instance of Order is passed to the initialize method and stored as an instance variable (using the # syntax : #order). This way, this variable can be accessed from other methods in the converter (the variable has the instance scope) :
class OrderConverter
def to_pdf
#order.items.each do |item|
# Write the order items to the PDF
end
end
end
The attr_reader is not strictly required, but is a convenient way to access the Order object from other methods :
class OrderConverter
def to_pdf
order.items.each do |item|
# Write the order items to the PDF
end
end
end
It will also allow you to get the reference to the order out of any converter instance :
converter.order
The # on the front of the variable makes it an instance variable. If it wasn't there the variable would just be a local variable. I'm guessing that since this is a book about Rails, it's assuming that this code would be in a controller. Variables that controllers want to share across methods or expose in their views need to be instance variables. If this is the case #order was probably created either via parameters from a request or with values pulled from the database.
This probably isn't that significant though, both his example and your example work - I think the author was just showing how a call to the OrderConverter would look, and ignored how the Order object got created.
attr_reader :order creates a "getter" method for the #order instance variable in OrderConverter - it's not needed for to_pdf - it would be used to get the Order back out of the OrderConverter via converter.order. I don't see any need to have this in the code you've given so far, but maybe there's some need for it later.

Rails/Ruby: don't understand this method

I'm reading a book called RailsAntiPatterns. In the converter method below, a new OrderConverter object is instantiated, and I assume self refers to an instance of Order class.
# app/models/order.rb
class Order < ActiveRecord::Base
def converter
OrderConverter.new(self)
end
end
# app/models/order_converter.rb
class OrderConverter
attr_reader :order
def initialize(order)
#order = order
end
def to_xml # ...
end
def to_json # ...
end
def to_csv # ...
end
def to_pdf # ...
end
end
Why instantiate a new class inside of converter?
Why does self need to be passed as an argument?
Can you summarize in lay terms what's going on?
Why instantiate a new class inside of converter?
Of course, it's up to the choice of the author, but it's probably convenient. For instance:
#my_order = Order.new
#my_order.converter.to_xml
That reads quite nicely, which is important in the eyes of a Rubyist. As the original designer of Ruby, Yukihiro Matsumoto (Matz) has said:
But in fact we need to focus on humans, on how humans care about doing programming or operating the application of the machines. We are the masters. They are the slaves.
Readibility for humans is, therefore, important if you wish to produce elegant Ruby code.
Why does "self" need to be passed as an argument?
Quite simply, OrderConverter requires an order to convert. Since the method converter is defined for instances of the Order class, an instance that wishes to convert itself will pass self as the argument to OrderConverter#new.
can you summarize in lay terms what's going on?
I hope the above has done that for you.
There's not much happening here.
def converter
OrderConverter.new(self)
end
this method creates a new OrderConverter and returns it. OrderConverter is passed a reference to the Order (self) that it can use to do its work (converting).
That's basically it.
he's returning a new instance of OrderConverter whenever you call the instance method "converter" from the Order class (it's an implicit return).
the constructor from OrderConverter takes an instance of Order as its first argument.
regarding the "why" questions, there's no real answer as far as Ruby is concerned, it's up to the implementator -i.e. the author- what the code actually does.

Resources