Class: Ciesta::Form

Inherits:
Object
  • Object
show all
Defined in:
lib/ciesta/form.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Form



17
18
19
20
21
22
23
24
25
# File 'lib/ciesta/form.rb', line 17

def initialize(object)
  self.object = object

  obj_values = fields.keys.each_with_object({}) do |key, mem|
    mem[key] = object.public_send(key)
  end

  assign(obj_values)
end

Instance Attribute Details

#objectObject

Returns the value of attribute object.



15
16
17
# File 'lib/ciesta/form.rb', line 15

def object
  @object
end

Class Method Details

.field(name, options = {}) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/ciesta/form.rb', line 3

def self.field(name, options = {})
  name = name.to_sym
  fields[name] ||= Ciesta::Field.new(name, options)

  define_method(name) { self.class.fields[name].value }
  define_method("#{name}=") { |value| self.class.fields[name].value = value }
end

.validate(&block) ⇒ Object



11
12
13
# File 'lib/ciesta/form.rb', line 11

def self.validate(&block)
  validator.use(&block)
end

Instance Method Details

#assign(params) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/ciesta/form.rb', line 38

def assign(params)
  keys = fields.keys
  params.keep_if { |key, _value| keys.include?(key) }
  begin
    assign!(params)
  rescue StandardError
    nil
  end
end

#assign!(attributes) ⇒ Object



32
33
34
35
36
# File 'lib/ciesta/form.rb', line 32

def assign!(attributes)
  attributes.each { |key, value| send("#{key}=", value) }
rescue NoMethodError => e
  raise Ciesta::FieldNotDefined, e.message
end

#errorsObject



48
49
50
# File 'lib/ciesta/form.rb', line 48

def errors
  validator.errors
end

#syncObject



61
62
63
64
65
# File 'lib/ciesta/form.rb', line 61

def sync
  sync!
rescue StandardError
  nil
end

#sync! {|object| ... } ⇒ Object

Yields:

Raises:



52
53
54
55
56
57
58
59
# File 'lib/ciesta/form.rb', line 52

def sync!
  raise Ciesta::NotValid, 'Form is not valid' unless errors.empty?

  fields.each { |name, field| object.send("#{name}=", field.value) }

  yield(object) if block_given?
  true
end

#valid?(params = nil) ⇒ Boolean



27
28
29
30
# File 'lib/ciesta/form.rb', line 27

def valid?(params = nil)
  assign(params) if params
  validator.valid?(attributes)
end