Class accessors and inheritance in Ruby on Rails - ruby-on-rails

Like the following code shows, having class accessors defined in the superclass could have unexpected behaviours because the class accessor is the same variable for all the subclasses.
class Super
cattr_accessor :name
end
class SubA < Super; end
class SubB < Super; end
SubA.name = "A"
SubB.name = "B"
SubA.name
=> "B" # unexpected!
I want to have an independent class accessor for each subclass, so a possible solution is moving the cattr_accessor from the superclass and putting it in every subclass.
class Super; end
class SubA < Super
cattr_accessor :name
end
class SubB < Super
cattr_accessor :name
end
SubA.name = "A"
SubB.name = "B"
SubA.name
=> "A" # expected!
It is this solution a good practice? Do you know better alternatives?

Open up Super's singleton class and give that a regular attr_accessor:
class Super
class << self
attr_accessor :name
end
end
That should give you the semantics you want: a "class level instance variable".
However I'll note that any value set for :name on Super will not be inherited by Super's children. This makes sense if you think about it: the children inherit the attr_accessor, not the attribute itself.
There are some ways around this, most notably rails provides class_attribute which provides the ability of children to inherit the value of the parent's attribute unless explicitly overridden.

Related

Rails - attr_accessor :- read the attribute value instead of the function overriding it

I have a model Customer that accepts a virtual attribute opening_balance. Code looks something like this:
model Customer < ApplicationRecord
attr_accessor :opening_balance
has_one :ledger_account
after_create :open_ledger_account
def opening_balance
ledger_account.opening_balance if ledger_account.present?
end
private
def open_ledger_account
create_ledger_account!(opening_balance: self.opening_balance)
end
But the issue here is self.opening_balance is calling the method defined in the class not the value stored in attr_accessor's opening_balance attribute.
I tried one more solution:
def open_ledger_account
create_ledger_account!(opening_balance: self.read_attribute(:opening_balance))
end
But this also doesn't work.
How to read the value stored in the actual attribute? Any help would be appreciated. I am using rails 5.1.
Thanks!
attr_accessor defines a instance variable and a method to access it (read/write).
So the easy way is to write:
def open_ledger_account
create_ledger_account!(opening_balance: #opening_balance)
end
The read_attribute would only work if opening_balance was an attribute in the database on Customer.
First you have to understand that attr_accessor does not define instance variables. It just creates setter and getter methods. What attr_accessor :name does is:
class Person
def name
#name
end
def name=(value)
#name = value
end
end
Now you can access the instance variable from the outside:
p = Person.new
p.name = 'Jane'
puts p.name
And you can also access the instance variable from the inside by using the getter method instead of #name:
class Person
attr_accessor :name
def hello
"hello my name is: #{name}"
end
end
attr_accessor does not "define" a instance variable. There is no declaration of members/attributes in Ruby like in for example Java. An instance variables is declared when it is first set. Accessing an instance variable that has not been assigned a value returns nil.
So whats happing here:
class Customer < ApplicationRecord
attr_accessor :opening_balance
# ...
def opening_balance
ledger_account.opening_balance if ledger_account.present?
end
end
Is that you are overwriting the getter created by attr_accessor. If you want to access the instance variable itself just use #opening_balance.
However...
You should just use delegate instead:
class Customer < ApplicationRecord
has_one :ledger_account
delegate :opening_balance, to: :ledger_account
end

Why can't this inherited class attribute be assigned to?

I know in Ruby, unlike other languages, there is class method inheritance.
class A
def self.filter_by
"filter"
end
end
class B < A
end
B.filter_by => "filter"
B's singleton class inherits methods from A's singleton class, and it appears to inherit the instance variables of those class methods:
class A
class << self
attr_accessor :filter_by
end
end
class B < A
end
B.filter_by = "filter"
A.filter_by = "no_filter"
=> "no_filter"
B.filter_by # B's value is not changed
=> "filter"
But it does not inherit the values:
class A
class << self
attr_accessor :filter_by
end
end
class B < A
end
A.filter_by = "filter"
B.filter_by => nil
B did not inherit the value set to A's #filter_by instance variable.
It can be resolved this way using the built-in inherited hook, or in Rails you can use class_attribute:
class A < ActiveRecord::Base
class_attribute :filter_by
end
class B < A
end
A.filter_by = "filter"
=> "filter"
B.filter_by # Now B's #filter_by inherited the value set in A's #filter_by
=> "filter"
But what I don't understand is why I cannot do this:
class A < ActiveRecord::Base
class_attribute :filter_by
end
class B < A
filter_by= %w(user_id_is status_id_is task_category_id_is)
end
B.filter_by => nil
Why does it return nil in this situation and not in the other situation? In this case as well, I set a value on self when I declared B (which is the singleton object).
Keep in mind that in your last example, there is
A class attribute named filter_by(with corresponding filter_by and filter_by= methods (inherited from class A)
A locally scoped variable inside of class B called filter_by.
The variable filter_by is not available outside of the scoping, and is also not available inside class B methods of any kind. In class B, you've set this variable to the list of strings, but when you do B.filter_by, the method inherited from class A is called. This value has not yet been set, so nil is returned.
Had you done self.filter_by = %w(...) inside the class, then it would have accessed the method filter_by= and set the class attribute as you intended.
You just forgot self. when you assigned to the attribute. Ruby thought you were assigning to a local. Fix it with self.:
class A < ActiveRecord::Base
class_attribute :filter_by
end
class B < A
self.filter_by= %w(user_id_is status_id_is task_category_id_is)
end
B.filter_by => nil
=> ["user_id_is", "status_id_is", "task_category_id_is"]

Rails model -- non persistent class member or property?

Is it possible / advisable to have a member of a class that is not persisted to the database for a rails model?
I want to store the last type the user selects in a session variable. Since I cant set the session variable from my model, I want to store the value in a "dummy" class member that just passes the value back to the controller.
Can you have such a class member?
Adding non-persisted attributes to a Rails model is just like any other Ruby class:
class User < ActiveRecord::Base
attr_accessor :someattr
end
me = User.new(name: 'Max', someattr: 'bar')
me.someattr # "bar"
me.someattr = 'foo'
The extended explanation:
In Ruby all instance variables are private and do not need to be defined before assignment.
attr_accessor creates a setter and getter method:
class User < ActiveRecord::Base
def someattr
#someattr
end
def someattr=(value)
#someattr = value
end
end
There is one special thing going on here; Rails takes the hash you pass to User.new and maps the values to attributes. You could simulate this behavior in a plain ruby class with something like:
class Foo
attr_accessor :bar
def initialize(hash)
hash.keys.each do |key|
setter = "#{key}=".intern
self.send(setter, hash[key]) if self.respond_to? setter
end
end
end
> Foo.new(bar: 'baz')
=> <Foo:0x0000010112aa50 #bar="baz">
Classes in Ruby can also be re-opened at any point, ActiveRecord uses this ability to "auto-magically" add getters and setters to your models based on its database columns (ActiveRecord figures out which attributes to add based on the database schema).
Yes you can, the code below allows you to set my_class_variable and inside the model reference it as #my_class_variable
class MyCLass < ActiveRecord::Base
attr_accessor :my_class_variable
def do_something_with_it
#my_class_variable + 10
end

Subclassing ActiveRecord with permalink_fu in a rails engine

This question is related to extending class methods in Ruby, perhaps more specifically in the way that permalink_fu does so.
It appears that has_permalink on a model will not be available in a derived model. Certainly I would expect anything defined in a class to be inherited by its derived classes.
class MyScope::MyClass < ActiveRecord::Base
unloadable
self.abstract_class = true
has_permalink :name
end
class MyClass < MyScope::MyClass
unloadable
#has_permalink :name # This seems to be required
end
Is there something in the way permalink_fu mixes itself in that causes this issue?
I'm using the permalink-v.1.0.0 gem http://github.com/goncalossilva/permalink_fu
After investigating this, I can now see that the problem is related to how permalink_fu verifies it it should create a permalink or not. It verifies this by checking if the permalink_field of the class is blank or not.
What's the permalink_field? When you do
class Parent < ActiveRecord::Base
has_permalink :name
end
class Child < Parent
end
you can access the permalink by writing Parent.new.permalink or Child.new.permalink. This method name can be changed by writing
class Parent < ActiveRecord::Base
has_permalink :name 'custom_permalink_name'
end
If so, the permalink will be accessible by writing Parent.new.custom_permalink_name (or Child.new.custom_permalink_name).
What's the problem with this? The permalink_field accessor methods are defined on Parent's metaclass:
class << self
attr_accessor :permalink_field
end
When you run the has_permalink method, it calls Parent.permalink_field = 'permalink'.
The problem is that although the permalink_field method is available on all subclasses, its value is stored on the class it was called. This means that the value is not propagated to the subclasses.
So, as the permalink_field is stored on the Parent class, the Child does not inherit the value, although it inherits the accessor methods. As Child.permalink_field is blank, the should_create_permalink? returns false, and Child.create :name => 'something' does not create a permalink.
A possible solution would be to replace the attr_acessors on the metaclass with cattr_accessors on the class (lines 57 to 61 on the permalink_fu.rb file).
Replace
class << base
attr_accessor :permalink_options
attr_accessor :permalink_attributes
attr_accessor :permalink_field
end
with
base.cattr_accessor :permalink_options
base.cattr_accessor :permalink_attributes
base.cattr_accessor :permalink_field
Note that this will invalidate any possible customization on the subclass. You will no longer be able to specify different options for the subclasses, as these three attributes are shared by Parent and all its subclasses (and subsubclasses).

Rails attr_accessible does not work for :type?

Im trying set the single table inheritance model type in a form. So i have a select menu for attribute :type and the values are the names of the STI subclasses. The problem is the error log keeps printing:
WARNING: Can't mass-assign these protected attributes: type
So i added "attr_accessible :type" to the model:
class ContentItem < ActiveRecord::Base
# needed so we can set/update :type in mass
attr_accessible :position, :description, :type, :url, :youtube_id, :start_time, :end_time
validates_presence_of :position
belongs_to :chapter
has_many :user_content_items
end
Doesn't change anything, the ContentItem still has :type=nil after .update_attributes() is called in the controller. Any idea how to mass update the :type from a form?
we can override attributes_protected_by_default
class Example < ActiveRecord::Base
def self.attributes_protected_by_default
# default is ["id","type"]
["id"]
end
end
e = Example.new(:type=>"my_type")
You should use the proper constructor based on the subclass you want to create, instead of calling the superclass constructor and assigning type manually. Let ActiveRecord do this for you:
# in controller
def create
# assuming your select has a name of 'content_item_type'
params[:content_item_type].constantize.new(params[:content_item])
end
This gives you the benefits of defining different behavior in your subclasses initialize() method or callbacks. If you don't need these sorts of benefits or are planning to change the class of an object frequently, you may want to reconsider using inheritance and just stick with an attribute.
Duplex at railsforum.com found a workaround:
use a virtual attribute in the forms
and in the model instead of type
dirtectly:
def type_helper
self.type
end
def type_helper=(type)
self.type = type
end
Worked like a charm.
"type" sometimes causes troubles... I usually use "kind" instead.
See also: http://wiki.rubyonrails.org/rails/pages/ReservedWords
I followed http://coderrr.wordpress.com/2008/04/22/building-the-right-class-with-sti-in-rails/ for solving the same problem I had. I'm fairly new to Rails world so am not so sure if this approach is good or bad, but it works very well. I've copied the code below.
class GenericClass < ActiveRecord::Base
class << self
def new_with_cast(*a, &b)
if (h = a.first).is_a? Hash and (type = h[:type] || h['type']) and (klass = type.constantize) != self
raise "wtF hax!!" unless klass < self # klass should be a descendant of us
return klass.new(*a, &b)
end
new_without_cast(*a, &b)
end
alias_method_chain :new, :cast
end
class X < GenericClass; end
GenericClass.new(:type => 'X') # => #<X:0xb79e89d4 #attrs={:type=>"X"}>

Resources