It was the best of times; it was the worst of times...
I can relate. Figuring out odd code is like that; usually all at the same time.
Consider the first class
listed below, when run in a Rails console for my current test-bed app. When I run a Rails-console pry
session as...
$ bundle exec rails c
Loading development environment (Rails 4.2.0)
Frame number: 0/5
[1] pry(main)> ActiveRecord::Base.establish_connection
=> #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007f9d96a83e38
# ... elided; obviously successful...
[2] pry(main)> require_relative 'first_class.rb'
=> true
[3] pry(main)> foo = Foo.new name: 'User Name', email: 'user@example.com', profile: 'The Profile'
=> #<Foo:0x007f9d969833a8 @email="user@example.com", @name="User Name", @profile="The Profile">
[4] pry(main)> foo.valid?
=> true
[5] pry(main)> foo.instance_variable_set :@name, ' Bad Name '
=> " Bad Name "
[6] pry(main)> foo.valid? == false
=> true
[7] pry(main)> foo.errors.full_messages == ["Name may not have leading whitespace", "Name may not have trailing whitespace", "Name may not have adjacent whitespace"]
=> true
[8] exit
$
...everything works as I expect (as evidenced by the comparisons yielding => true
).
However, when I attempt to take what I've gleaned from the above and have a second try
, things go pear-shaped:
$ bundle exec rails c
Loading development environment (Rails 4.2.0)
Frame number: 0/5
[1] pry(main)> ActiveRecord::Base.establish_connection
=> #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007fdc165c6fa8
# ... elided; obviously successful...
[2] pry(main)> require_relative 'second_try.rb'
=> true
[3] pry(main)> bar = $bar
=> #<Object:0x007faf8167a628>
[4] pry(main)> bar.instance_variable_set :@name, 'User Name'
=> "User Name"
[5] pry(main)> bar.instance_variable_set :@email, 'user@example.com'
=> "user@example.com"
[6] pry(main)> bar.instance_variable_set :@profile, 'User Profile'
=> "User Profile"
[7] pry(main)> bar.valid? == true
=> true
[8] pry(main)> bar.instance_variable_set :@name, ' Bad Name '
=> " Bad Name "
[9] pry(main)> bar.valid? == false
=> true
So far, so good. Here's the problem:
[10] pry(main)> bar.errors.full_messages == ["Name may not have leading whitespace", "Name may not have trailing whitespace", "Name may not have adjacent whitespace"]
NoMethodError: undefined method `human_attribute_name' for Object:Class
from /Users/jeffdickey/src/rails/meldd/new_poc/vendor/ruby/2.2.0/gems/activemodel-4.2.0/lib/active_model/errors.rb:380:in `full_message'
[11] pry(main)> exit
$
I could understand ActiveModel bitching at me because I hadn't defined a method somewhere in my bolting-on-to-a-simple-Object
-instance except that it had no qualms about an (apparently) equivalently-constructed Class
instance.
What am I missing?
(For your convenience, the code in the app/entites/user/internals/name_validator.rb
file included by both source files is now included in this Gist for easy reference.)