Skip to content

Instantly share code, notes, and snippets.

@danhodge
Created October 3, 2011 19:29
Show Gist options
  • Save danhodge/1259998 to your computer and use it in GitHub Desktop.
Save danhodge/1259998 to your computer and use it in GitHub Desktop.
attr_* methods invoked from private methods behave differently in REE 1.8.7 and MRI 1.9.2
require 'rubygems'
require 'active_support'
module Attrs
extend ActiveSupport::Concern
module ClassMethods
def add_public_accessor(name)
add_accessor(name)
end
private
def add_accessor(name)
# in REE 1.8.7, attrs defined directly private methods still have public visibility
# in MRI 1.9.2, attrs defined directly in private methods have private visibility
attr_accessor name.to_sym
end
end
end
module EvalAttrs
extend ActiveSupport::Concern
module ClassMethods
def add_public_accessor(name)
add_accessor(name)
end
private
def add_accessor(name)
# in REE 1.8.7 and MRI 1.9.2, attrs defined usingher=' called forprivate method `bar=' called for visibility of the enclosing method
class_eval { attr_accessor name.to_sym }
end
end
end
# works in 1.8 but not 1.9
class ClassWithAttrs18
include Attrs
end
# works in 1.8 and 1.9
class ClassWithEvalAttrs
include EvalAttrs
end
ClassWithEvalAttrs.add_public_accessor('foo')
ev_attrs = ClassWithEvalAttrs.new
ev_attrs.foo = 'hello' # works in REE 1.8.7 and MRI 1.9.2
puts "foo = #{ev_attrs.foo}"
ClassWithAttrs18.add_public_accessor('bar')
attrs = ClassWithAttrs18.new
attrs.bar = 123 # fails with a private method `bar=' called for object (NoMethodError) in MRI 1.9.2
puts "bar = #{attrs.bar}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment