ruby - Accessing variable name -
i trying parameter validation outside of rails.
def create_statement(action, ...) valid_one_of(action, ['add', 'move', 'delete']) ... end
validation method:
def valid_one_of(input, valid_values) return true if valid_values.include?(input) raise "#{input} not valid value #{input.var_name}" end
sample call:
create_statement('bob')
so output be:
bob not valid value action
the problem how input.var_name ?
i workaround pass
valid_one_of(action, ['add', 'move', 'delete'], 'action')
(and use 3rd parm output) doesn't seem feels bit redundant.
if not possible access variable name there more dry coding style workaround?
i don't know of way name of local variable, , if could, name want? name of parameter define on method definition? name of variable in caller?
i don't think "work-around" horrible, suggest couple of slight variations might read little better.
also not sure if intent pass in list of valid values @ call site, or if might have, hash of valid values might use passed in type valid values from.
def valid_one_of_type type, input:, valid_values: return true if valid_values.include?(input) raise "#{input} not valid value #{type}" end my_action = "bob" valid_one_of_type :action , input: my_action, valid_values: ['add', 'move', 'delete'] def valid_one_of_type type, input, valid_values return true if valid_values.include?(input) raise "#{input} not valid value #{type}" end my_action = "bob" valid_one_of_type :action , my_action, ['add', 'move', 'delete']
another option wrap actions in class , validations on creation:
class action valid_actions = ['add', 'move', 'delete'] def initialize action unless valid_actions.include? action raise "#{action} not valid value #{self.class.name}" end end end my_action = action.new "bob"
Comments
Post a Comment