Initializer destroying information
I have a variable bill that I send to a hash:
bill = Hash 'number' -> 2017 'bill_type' -> h 'sponsor_id' -> 400004 and 23 more keys
this is passed to an initializer:
Bill.new(bill) and the result is an object with no data:
# and Bill.new(bill).to_json = {}
module GovKit module OpenCongress class Bill < OpenCongressObject attr_accessor :bill_type, :id, :introduced, :last_speech, :last_vote_date, :last_vote_roll, :last_vote_where, :last_action, :number, :plain_language_summary, :session, :sponsor, :co_sponsors, :title_full_common, :status, :most_recent_actions, :bill_titles, :recent_blogs, :recent_news, :ident def initialize(params) params.each do |key, value| instance_va开发者_StackOverflowriable_set("@#{key}", value) if Bill.instance_methods.include? key end end ...
I am able to watch inside the initialize function, and the keys are defined, but the initializer consistently produces a consistently empty object. I am using rails 3.0.7, rubygems 1.6.2 and ruby "ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.7.0]".
You may want to try adding attr_accessible for those fields. Perhaps ruby/rails is smart enough to protect you from your own mass assignment.
I found it. The gem author assumed that JSON.parse produced symbols to act as keys. Now the json gem produces strings as keys. Adding the to_sym below makes it work.
instance_variable_set("@#{key}", value) if Bill.instance_methods.include? key.to_sym
精彩评论