handle relationships with no data #14

Closed
evansj opened this Issue May 29, 2012 · 2 comments

Projects

None yet

2 participants

@evansj
evansj commented May 29, 2012

Some of the data I get back from the server will have nil data. e.g.

class Token
  include Her::Model

  has_one :user
end
{ "id": "...", "user":null, ... }
% rails c          
Loading development environment (Rails 3.2.3)
1.9.3p194 :001 > t = Token.get("token", :site_key =>'site')
(Object doesn't support #inspect)
 =>  
1.9.3p194 :003 > t.inspect
NoMethodError: undefined method `include?' for nil:NilClass
    from [...]/gems/her-0.2/lib/her/model/introspection.rb:15:in `inspect'
    from [...]/gems/her-0.2/lib/her/model/introspection.rb:27:in `attribute_for_inspect'
    from [...]/gems/her-0.2/lib/her/model/introspection.rb:16:in `block in inspect'
    from [...]/gems/her-0.2/lib/her/model/introspection.rb:16:in `each'
    from [...]/gems/her-0.2/lib/her/model/introspection.rb:16:in `inject'
    from [...]/gems/her-0.2/lib/her/model/introspection.rb:16:in `inspect'
    from (irb):3
    from [...]/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
    from [...]/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
    from [...]/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

The problem is that it tries to set t.user to a new instance of User, but passes nil to the constructor. Introspection#inspect then raises NoMethodError when accessing @data.inspect? because @data is nil.

I have a simple fix which I can give you a pull request for:

diff --git a/lib/her/model/relationships.rb b/lib/her/model/relationships.rb
index 5f98cbc..0489b65 100644
--- a/lib/her/model/relationships.rb
+++ b/lib/her/model/relationships.rb
@@ -16,7 +16,7 @@ module Her
           relationships.each do |relationship|
             name = relationship[:name]
             class_name = relationship[:class_name]
-            next unless data.include?(name)
+            next if data[name].blank?
             data[name] = case type
               when :has_many
                 Her::Model::ORM.initialize_collection(class_name, data[name])

With that patch applied the inspect method works fine again, and t.user returns nil.

However, this breaks a lot of tests which expect a null instance of a relationship class to be instantiated even if there is no data. Let me know your thoughts.

Thanks for the library though, it's going to be extremely useful!

@remiprev remiprev closed this in 7818032 May 29, 2012
@remiprev
Owner

I was able to add a non-passing example and fix it with code based on your diff — thank you!

@evansj
evansj commented May 29, 2012

Great - thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment