ruby on rails - Safe way to initialize attributes from a yaml or hash -
in initialize method trying write can pass either hash or yaml object init attribute values.
my yaml file looks like:
defaults: &defaults host: localhost port: 4565 timeout: 3 development: <<: *defaults test: <<: *defaults staging: <<: *defaults production: <<: *defaults
i have this:
def initialize(options) if options.respond_to? "has_key" && options.has_key? "defaults" config = options["defaults"] else config = options end @hostname = config[:hostname] @port = config[:port] @timeout = config[:timeout] end
this not working me, i'm getting error:
unexpected tstring_beg, expecting keyword_then or ';' or '\n' if options.respond_to? "has_key" && options.has_key? "defaults"
- how can load correct environment also? (test, development, production)
- how can throw error if 1 of keys isn't present? (or @ least major ones need sure hostname, port)
you need parenthesize if statement.
if options.respond_to?("has_key") && options.has_key?("defaults")
Comments
Post a Comment