Reputation: 1492
I'm trying to implement a gem that is redis wrapper for other library i.e to store the ruby object in the redis.
all work well but what I want is when I do
[Class].all
It give object like this
[#<Peagon:0x007fba589de3a0 @name="a", @omg=false ,@payload="one",@handler="--- one\n...\n"> ,#<Peagon:0x007fba589de1a0 @name="b", @omg=true,@payload="two",@handler="--- two\n...\n">]
but instead I want it to be look like how active record present the object
[#<Peagon name: "a",omg: false ,handler: "--- one\n...\n"> ,#<Peagon name="b", omg: true,handler: "--- two\n...\n">]
The reason for this that I not interested in showing the user the @payload
instance variable because that is something set by the other library
so basically like this happen [My gem]
class Peagon
include SomeModule
attr_accessor :name,:omg,:handler
def initialize(options)
@name = options[:name]
@omg = options
self.payload_object = options[:payload_object]
end
end
Now the [Other Library] has this module
in it
module SomeModule
def payload=(object)
@payload ||= object
self.handler = @payload.to_yaml
end
def payload
@payload ||= YAML.load(self.handler)
end
end
Overwriting the payload method from other library is not in my mind
Now is it possible to get what I meant above
Upvotes: 0
Views: 132
Reputation: 434795
Looks like you just want to adjust what irb
, the Rails console, and friends will display for objects of your class. If so, they just call inspect
:
inspect → string
Returns a string containing a human-readable representation of obj. By default, show the class name and the list of the instance variables and their values (by calling inspect on each of them). User defined classes should override this method to make better representation of obj.
So all you need to do is provide your own inspect
implementation, something like:
def inspect
"#<#{class} name: #{@name.inspect} ...>"
end
Upvotes: 1