Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Add `#inspect` and `.accessors` #1

Merged
merged 2 commits into from

3 participants

Justin French Steve Hodgkiss Ryan Allen
Justin French

Hello, I wanted to get something hash-like back from MyModel#inspect. Previously, #inspect just delegated to #to_s, which I think is the default behaviour for Kernal#to_s. This is now way more bettererer, returning a hash of method names and values so that I can, you know, inspect stuff.

>> User.new(:name => "Joe").inspect
=> { :name => "Joe" }
Steve Hodgkiss
Collaborator

+1

Steve Hodgkiss stevehodgkiss merged commit d1bff1f into from
Justin French

@ryan-allen we regret that remark

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 23 additions and 0 deletions.
  1. +13 −0 lib/modelling.rb
  2. +10 −0 spec/modelling_spec.rb
13 lib/modelling.rb
View
@@ -32,6 +32,10 @@ def structs(*args)
def members
@members ||= {}
end
+
+ def accessors
+ @accessors ||= []
+ end
private
@@ -55,6 +59,7 @@ def generate_accessors(names_to_initializer)
end
def create_accessor(name)
+ accessors << name
instance_eval { attr_accessor name }
end
@@ -74,5 +79,13 @@ def initialize(args = {})
end
args.each { |name, value| send "#{name}=", value }
end
+
+ def inspect
+ hash = {}
+ self.class.accessors.each do |method_name|
+ hash[method_name] = send(method_name)
+ end
+ hash
+ end
end
10 spec/modelling_spec.rb
View
@@ -125,6 +125,16 @@ class LambdaTest
it 'doesnt fail when lambdas with no args are used' do
LambdaTest.new.lambda.should eq 'boo'
end
+
+ specify 'tracks list of accessors' do
+ User.accessors.should include :name, :age
+ end
+
+ specify 'provides a Hash of attributes and values through inspect' do
+ User.new.inspect.key?(:name).should be_true
+ User.new.inspect.key?(:age).should be_true
+ User.new(:name => "Joe").inspect[:name].should eq "Joe"
+ end
context 'inheritence' do
let(:car) { Car.new }
Something went wrong with that request. Please try again.