Class: Resourced::Attributes::RuleSet

Inherits:
Object
  • Object
show all
Defined in:
lib/resourced/attributes.rb

Direct Known Subclasses

Finders::Finders

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRuleSet

Returns a new instance of RuleSet.



57
58
59
60
61
62
63
64
# File 'lib/resourced/attributes.rb', line 57

def initialize
  @types                   = {}
  @defaults                = {}
  @conditional_allows      = []
  @unconditional_allows    = []
  @conditional_restricts   = []
  @unconditional_restricts = []
end

Instance Attribute Details

#defaultsObject (readonly)

Returns the value of attribute defaults.



65
66
67
# File 'lib/resourced/attributes.rb', line 65

def defaults
  @defaults
end

Instance Method Details

#allow(*fields) ⇒ Object

Allow field(s) to be assigned

Options:

  • default Default value

  • if Proc Condition for allowing, should return Boolean

Examples:

allow :name, :email, if: -> { scope == :admin }
allow :role, default: "guest"


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/resourced/attributes.rb', line 79

def allow(*fields)
  opts = extract_options(fields)

  if opts[:if]
    @conditional_allows << ConditionalGroup.new(opts[:if], fields)
  else
    @unconditional_allows += fields
  end

  if as = opts[:as]
    fields.each do |field|
      @types[field] = :"to_#{as}"
    end
  end

  if opts[:default]
    fields.each do |field|
      @defaults[field] = opts[:default]
    end
  end

  self
end

#restrict(*fields) ⇒ Object

Restrict allowed fields

Options:

  • if Proc Condition for restriction, should return Boolean

Examples:

restrict :role, if: -> { scope !== :admin }


113
114
115
116
117
118
119
120
121
122
123
# File 'lib/resourced/attributes.rb', line 113

def restrict(*fields)
  opts = extract_options(fields)

  if opts[:if]
    @conditional_restricts << ConditionalGroup.new(opts[:if], fields)
  else
    @unconditional_restricts += fields
  end

  self
end

#sanitize_params(context, params) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/resourced/attributes.rb', line 125

def sanitize_params(context, params)
  allowed_params = @unconditional_allows

  @conditional_allows.each do |cond|
    if cond.test(context)
      allowed_params += cond.fields
    end
  end

  allowed_params.uniq!

  allowed_params -= @unconditional_restricts

  @conditional_restricts.each do |cond|
    if cond.test(context)
      allowed_params -= cond.fields
    end
  end

  result = {}
  coercer = Coercible::Coercer.new unless @types.empty?

  @defaults.merge(params).each do |k, v|
    k = k.to_sym

    if allowed_params.include?(k)
      result[k] = @types[k] ? coercer[v.class].public_send(@types[k], v) : v
    end
  end

  result
end