How do I create an attribute accessor to do this...

J

J2M

I want to be able to do this to merge a hash into attribute bas on
instance bar in class foo;

bar = Foo.new
bar.bas << { :this => "that" }

Is there any way to define the accessor in Foo to be able to do this?

Thanks,
James
 
T

Trans

J2M said:
I want to be able to do this to merge a hash into attribute bas on
instance bar in class foo;

bar = Foo.new
bar.bas << { :this => "that" }

Is there any way to define the accessor in Foo to be able to do this?

Thanks,
James

class Hash
alias :<<, :merge!
end

class Foo
attr :bas
def initialize
@bas = {}
end
end

Is that what you had in mind?

T.
 
D

dblack

Hi --

I want to be able to do this to merge a hash into attribute bas on
instance bar in class foo;

bar = Foo.new
bar.bas << { :this => "that" }

Is there any way to define the accessor in Foo to be able to do this?

Here's one way. It involves assigning a hash to @bar, and adding the
<< behavior to that hash (using a module).

require 'test/unit'

class Foo

attr_reader :bas

module UpdateAppender
def <<(other)
update(other)
end
end

def initialize
@bas = {}.extend(UpdateAppender)
end

end


class TestMerging < Test::Unit::TestCase
def test_1
f = Foo.new
f.bas << { :this => "that" }
assert_equal(f.bas.keys, [:this])
end
end


David

--
David A. Black | (e-mail address removed)
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
 
J

J2M

Thank you both for such quick responses. I will give this a go tomorrow
(v. late here in the UK).

David - thank you for all the time you take to help out us newbies, and
thank you for RailsConf Europe too - fan-tas-tic!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top