Skip to content

Instantly share code, notes, and snippets.

@VictorTpo
Last active January 20, 2016 16:32
Show Gist options
  • Save VictorTpo/6b99b9cceba1082f8b18 to your computer and use it in GitHub Desktop.
Save VictorTpo/6b99b9cceba1082f8b18 to your computer and use it in GitHub Desktop.
class Vilain
  attr_accessor :name, :kills
end
class VilainPresenter
  include ActionView::Helpers::NumberHelper
  
  def initialize(vilain)
    @vilain = vilain
  end
  
  def show_number(value)
    number_with_delimiter(value, delimiter: ' ')
  end
end
vilain = Vilain.new(name: 'Joker', kills: 444719)
pres_vilain = VilainPresenter.new(vilain)
pres_vilain.show_number(pres_vilain.kills)
> undefined method kills for VilainPresenter
class VilainPresenter
  include ActionView::Helpers::NumberHelper
  attr_accessible :kills
  [...]
end
pres_vilain.show_number(pres_vilain.kills)
> nil
class VilainPresenter
  include ActionView::Helpers::NumberHelper
  attr_accessible :kills
  def initialize(vilain)
    @vilain = vilain
    @kills = @vilain.kills
  end
end
pres_vilain.show_number(pres_vilain.kills)
> 444 719

But what if there is a lot of attributes, such as weapon, nickname, city, unvivers, nemesis . . . ?

class VilainPresenter
  include ActionView::Helpers::NumberHelper
  # attr_accessible :kills
  
  def initialize(vilain)
    @vilain = vilain
    set_instance_variables
    create_readers
  end
  [...]
  private
  
  def  set_instance_variables
    @vilain.attribute_names.each do |attribute|
      instance_variable_set("@#{attribute}", @row.send(attribute))
    end
  end
  
  def create_readers
    @vilain.attribute_names.each do |attribute|
      define_singleton_method(
        attribute.to_sym
      ) { instance_variable_get("@#{attribute}") }
    end
  end
end
pres_vilain.show_number(pres_vilain.kills)
> 444 719
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment