我可以让Rails这个代码更优雅吗?

时间:2014-03-24 08:43:49

标签: ruby-on-rails ruby-on-rails-4

我有这堂课:

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

我这样用它:

def help
    employee = User.new
    employee.name = "Dude"
    employee.email  = "Dude@gmail.com"
    employee.hr_id = "129836561"
    @employee = employee.print_employee
end

我的问题是,如何让help中的代码更短更优雅?

我试过了:

employee = User.new('dude','dude@gmail.com','129836561')
@employee = employee.print_employee 

但我有错误。

3 个答案:

答案 0 :(得分:3)

您正在寻找after_initialize和/或after_find回调。请参阅docs

after_initialize :set_default_values

private

def set_default_values
  self.name ||= 'Missing name'
end

注意

正如apneadiving所提到的,这不是解决问题的正确方法,但我认为这是您的问题的最佳答案如何使代码更优雅。为了获得最佳实践,请搜索服务类,如apneadiving的答案以及如何在控制器中使用它们来设置默认值。

答案 1 :(得分:1)

这样做:

class UserBuilder

  attr_reader :params

  def initialize(params = {})
    @params = params
  end

  def build
    User.new(default_params.merge(params))
  end

  def default_params
    {
      :name => "Missing Name",
      :email => "Missing Email",
      :hr_id => "Missing HR ID"
    }
  end
end

然后:

UserBuilder.new.build

或者:

UserBuilder.new({:name => 'foo'}).build

答案 2 :(得分:0)

所以我在Google上搜索了类似&#34; ActiveRecord默认值&#34;之类的东西,我找到的其中一件事就是这个Ruby宝石应该为你设置这个,所以它可能值得一试:default_value_for

来自文档的示例用法:

class User < ActiveRecord::Base
  default_value_for :name, "(no name)"
  default_value_for :last_seen do
    Time.now
  end
end

u = User.new
u.name       # => "(no name)"
u.last_seen  # => Mon Sep 22 17:28:38 +0200 2008