lib/parameters/parameters.rb in parameters-0.1.6 vs lib/parameters/parameters.rb in parameters-0.1.7

- old
+ new

@@ -146,17 +146,21 @@ # # Initalizes the parameters of the object using the given # _values_, which can override the default values of # parameters. # - def initialize_parameters + def initialize_params(values={}) self.class.each_param do |param| # do not override existing instance value if present - unless instance_variable_get("@#{param.name}".to_sym) + if instance_variable_get("@#{param.name}".to_sym).nil? begin if param.value.kind_of?(Proc) - value = param.value.call() + value = if param.value.arity > 0 + param.value.call(self) + else + param.value.call() + end else value = param.value.clone end rescue TypeError value = param.value @@ -165,25 +169,21 @@ instance_variable_set("@#{param.name}".to_sym,value) end self.params[param.name] = InstanceParam.new(self,param.name,param.description) end + + self.params = values if values.kind_of?(Hash) end # - # Initializes the parameters using initialize_parameters. If a +Hash+ + # Initializes the parameters using initialize_params. If a +Hash+ # is passed in as the first argument, it will be used to set the values # of parameters described within the Hash. # def initialize(*args,&block) - initialize_parameters - - values = args.first - - if values.kind_of?(Hash) - self.params = values - end + initialize_params(args.first) end # # Adds a new parameters with the specified _name_ and the given # _options_ to the object. @@ -196,16 +196,29 @@ # # obj.parameter('var',:default => 3, :description => 'my variable') # def parameter(name,options={}) name = name.to_sym + default = options[:default] + description = options[:description] + # resolve the default value + if default.kind_of?(Proc) + value = if default.arity > 0 + default.call(self) + else + default.call() + end + else + value = default + end + # set the instance variable - instance_variable_set("@#{name}".to_sym,options[:default]) + instance_variable_set("@#{name}".to_sym,value) # add the new parameter - self.params[name] = InstanceParam.new(self,name,options[:description]) + self.params[name] = InstanceParam.new(self,name,description) instance_eval %{ # define the reader method for the parameter def #{name} instance_variable_get("@#{name}".to_sym) @@ -326,10 +339,10 @@ # def require_params(*names) names.each do |name| name = name.to_s - unless instance_variable_get("@#{name}".to_sym) + if instance_variable_get("@#{name}".to_sym).nil? raise(Parameters::MissingParam,"parameter #{name.dump} has no value",caller) end end return true