Class: Presenter

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::Conversion, ActiveModel::Validations, Enumerable
Defined in:
lib/liaison/presenter.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_name, opts = {}) ⇒ Presenter

Constructs a new Presenter object which can be passed to a form or generally filled with values. It must take a model name, which is a string that is the name of the model you are presenting. It can also take a validator and fields.

Presenter.new('sign_up',
              :fields => [:account_name, :email, :password],
              :validator => SignUpValidator)


19
20
21
22
23
24
25
26
# File 'lib/liaison/presenter.rb', line 19

def initialize(model_name, opts = {})
  @@model_name = model_name

  @validator = opts[:validator]
  @fields   = opts[:fields]

  self.class.send(:attr_accessor,*@fields) unless @fields.nil? || @fields.empty?
end

Class Method Details

.model_nameObject

This only exists for ActiveModel::Naming



29
30
31
32
# File 'lib/liaison/presenter.rb', line 29

def self.model_name # :nodoc:
  model_namer = Struct.new("ModelNamer", :name).new(@@model_name)
  ActiveModel::Name.new(model_namer)
end

Instance Method Details

#[](key) ⇒ Object

Access individual values as if this were the CGI params hash.

@sign_up_presenter[:account_name]


73
74
75
# File 'lib/liaison/presenter.rb', line 73

def [](key)
  to_hash[key]
end

#add_errors(errs) ⇒ Object

Combine error messages from any ActiveModel object with the presenter’s, so they will show on the form.

@sign_up_presenter.add_errors(.errors)

You will probably use it like this:

class SignUp
  attr_accessor :presenter
  def save
     = Account.new
    .save.tap do |succeeded|
      presenter.add_errors(.errors) unless succeeded
    end
  end
end


66
67
68
# File 'lib/liaison/presenter.rb', line 66

def add_errors(errs)
  errs.each {|k,v| errors.add(k,v)}
end

#each(&block) ⇒ Object

Presenter objects are instances of Enumerable, which means you can iterate over the keys and values as set by the form.

@sign_up_presenter.each {|k,v| puts "the form set #{k} to #{v}" }


81
82
83
# File 'lib/liaison/presenter.rb', line 81

def each(&block)
  to_hash.each(&block)
end

#persisted?Boolean

This only exists for ActiveModel::Constructs

Returns:

  • (Boolean)


35
36
37
# File 'lib/liaison/presenter.rb', line 35

def persisted? # :nodoc:
  false
end

#with_params(params = {}) ⇒ Object

Set the params from the form using this.

For example, if you have a presenter in the @sign_up_presenter variable, you can update the values in it using this method:

@sign_up_presenter.with_params(params[:sign_up])


45
46
47
48
# File 'lib/liaison/presenter.rb', line 45

def with_params(params = {})
  params.each {|k,v| self.send("#{k}=", v)}
  self
end