Module: Phlexible::Rails::ControllerVariables::ClassMethods

Defined in:
lib/phlexible/rails/controller_variables.rb

Instance Method Summary collapse

Instance Method Details

#controller_variable(*names, **kwargs) ⇒ Object

/*



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/phlexible/rails/controller_variables.rb', line 68

def controller_variable(*names, **kwargs)
  if names.empty? && kwargs.empty?
    raise ArgumentError, 'You must provide at least one variable name and/or a hash of ' \
                         'variable names and options.'
  end

  allow_undefined = kwargs.delete(:allow_undefined)
  as = kwargs.delete(:as)

  if names.count > 1 && as
    raise ArgumentError, 'You cannot provide the `as:` option when passing multiple ' \
                         'variable names.'
  end

  names.each do |name|
    name_as = as || name
    name = "#{name}!" unless allow_undefined

    self.__controller_variables__ += { name.to_s => name_as.to_s }
  end

  kwargs.each do |k, v|
    if v.is_a?(Hash)
      name = v.key?(:as) ? v[:as].to_s : k.to_s

      if v.key?(:allow_undefined)
        k = "#{k}!" unless v[:allow_undefined]
      elsif !allow_undefined
        k = "#{k}!"
      end
    else
      name = v.to_s
      k = "#{k}!" unless allow_undefined
    end

    self.__controller_variables__ += { k.to_s => name }
  end
end