Created
July 4, 2009 17:25
-
-
Save softprops/140642 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example of inject method in ruby | |
class Foo | |
attr_accessor :title, :content, :posted_at | |
def initialize(title, content, posted_at) | |
@title, @content, @posted_at = title, content, posted_at | |
end | |
def serializeable_attributes | |
[:title, :content, :posted_at] | |
end | |
# serialize target attributes of the instance to a Hash | |
def to_h | |
attributes = serializeable_attributes | |
# inject takes an argument that will be the object you will be operating on, | |
# in this case, a new Hash. A block is given and passed two arguments; the current state | |
# of the object passed to inject and the current iterator value. | |
attributes.inject({}) { |hash, attribute| | |
# create a hash entry keyed by the name of the attribute and the value associated with | |
# the current instance | |
hash[attribute] = self.send(attribute) if respond_to? attribute | |
# it is important in this case to always return the current state | |
# of the hash for the next iteration | |
hash | |
} | |
end | |
end | |
p Foo.new('i am the title','i am the content', Time.now).to_h #=> {:title=>"i am the title", :content=>"i am the content", :posted_at=>Sat Jul 04 13:18:32 -0400 2009} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment