在 Rails 重构 Ruby 中的一些模型方法

Refactor some model methods in Ruby on Rails

我的模型中有一些方法可用于访问视图中存储的文本哈希:

class CarSpec < ActiveRecord::Base

    @@fuel_type_select_data = Hash[(1..5).to_a.zip(['Petrol', 'Diesel', 'Gas/petrol', 'Hybrid', 'Electric'])]
    @@mileage_type_select_data = Hash[(1..2).to_a.zip(['km', 'miles'])]
    @@transmission_select_data = Hash[(1..3).to_a.zip(['Manual', 'Automatic', 'Tiptronic'])]
    @@wheel_drive_data = Hash[(1..3).to_a.zip(['Front', 'Rear', 'All'])]
    @@color_data = Hash[(1..8).to_a.zip(['black', 'white', 'beige', 
              'blue', 'yellow', 'green', 'red', 'silver'])]

    def text_for_fuel_type
       @@fuel_type_select_data[fuel_type] 
    end

    def text_for_mileage_type
       @@mileage_type_select_data[mileage_type] 
    end

    def text_for_transmission
       @@transmission_select_data[transmission] 
    end

    def text_for_wheel_drive
       @@wheel_drive_data[wheel_drive] 
    end

    def text_for_color
       @@color_data[color]
    end

    def text_for_interior_color
       @@color_data[interior_color] 
    end

目前,我需要为每个字段编写一个新方法。我怎样才能重构这些方法,这样我就不需要为每个字段都写一个新方法了?请包括如何在视图中调用新 method/s。

使用常量而不是 class 变量会更好。

一个例子:

class CarSpec < ActiveRecord::Base
  WHEEL_DRIVE_DATA = {'Front' => 1}

  # remaining class code
end

查看示例代码:

<%= CarSpec::WHEEL_DRIVE_DATA['Front'] %>

同意@Humza 的观点:这里常量优于 class 变量。

当前的方法集可以动态定义 - 使用一些元编程魔法 - 如下:

fields = %w{ fuel_type mileage_type transmission wheel_drive interior_color }
fields.each do |field|
  define_method("text_for_#{field}") do
    CarSpec.class_variable_get("@@#{field}_select_data").send(:[], eval(field))
  end 
end 

注: 为了使上述工作正常,所有字段的 class 变量必须与 @@#{field}_select_data 名称一致;所以 @@wheel_drive_data 应该改为 @@wheel_drive_select_data,等等