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