Can i make Rails this code more elegant? -
i have class:
class user < activerecord::base attr_accessor :name, :email, :hr_id def initialize(attributes = {:name => "missing name",:email => "missing email",:hr_id => "missing hr id"}) @name = attributes[:name] @email = attributes[:email] @hr_id = attributes[:hr_id] end def print_employee "employee no: #{@hr_id} - #{@name} (#{@email})" end end
and use this:
def employee = user.new employee.name = "dude" employee.email = "dude@gmail.com" employee.hr_id = "129836561" @employee = employee.print_employee end
my question is, how can make code in help
shorter , more elegant?
i tried:
employee = user.new('dude','dude@gmail.com','129836561') @employee = employee.print_employee
but got errors.
you looking after_initialize
and/or after_find
callbacks. see docs
after_initialize :set_default_values private def set_default_values self.name ||= 'missing name' end
note
as apneadiving has mentioned, not correct way approach problem think best answer question how make code more elegant. best practice, search service classes apneadiving's answer , how use them in controller set default values.
Comments
Post a Comment