How to Replicate Class_Inheritable_Accessor's Behavior in Rails 3.1

How do I replicate class_inheritable_accessor's behavior in Rails 3.1?

class_attribute won't pollute its parent if it's used as intended. Make sure you're not changing the mutable items in-place.

types_and_classes.keys.each do |t|
self.presented = presented.merge({t => types_and_classes[t]})
end

Inherit class-level instance variables in Ruby?

Use a mixin:

module ClassLevelInheritableAttributes
def self.included(base)
base.extend(ClassMethods)
end

module ClassMethods
def inheritable_attributes(*args)
@inheritable_attributes ||= [:inheritable_attributes]
@inheritable_attributes += args
args.each do |arg|
class_eval %(
class << self; attr_accessor :#{arg} end
)
end
@inheritable_attributes
end

def inherited(subclass)
@inheritable_attributes.each do |inheritable_attribute|
instance_var = "@#{inheritable_attribute}"
subclass.instance_variable_set(instance_var, instance_variable_get(instance_var))
end
end
end
end

Including this module in a class, gives it two class methods: inheritable_attributes and inherited.

The inherited class method works the same as the self.included method in the module shown. Whenever a class that includes this module gets subclassed, it sets a class level instance variable for each of declared class level inheritable instance variables (@inheritable_attributes).

how to get rid of this plugin's class_inheritable_attribute deprecation warning?

Fork the plugin on GitHub and find the calls to class_inheritable_attribute and change them to class_attribute. Remove the old plugin from your vendor/plugins directory and add the new one. That would remove the deprecation warning.

ActiveRecord to_i method removed in Rails 3.2.9

The #to_i method never existed, however the way assigning objects to values has changed in Rails 3.2.8.

Given the following:

class Lecture < ActiveRecord::Base
has_one :professor
end

Previously you could assign a professor to a lecture like this:

@lecture.professor = Professor.find_by_id(1)

Or like this:

@lecture.professor_id = Professor.find_by_id(1)

In the first case everything is simple as the professor association expects a professor object. In the second case though ActiveRecord performed some magic to coerce the id from the professor, as professor_id expects a integer instead.

In Rails 3.2.8 and above that magic no longer works. It is nice in a way as it is a hint you are probably doing something wrong. For example, if there isn't a professor_id column in the database, but just professor which expects an integer, assigning like this will no longer work.

It looks like this will be reverted to the previous behaviour in Rails 3.2.11.



Related Topics



Leave a reply



Submit