如何在ruby中达到以下要求?

时间:2014-10-20 18:31:22

标签: ruby configuration arguments block metaprogramming

@custom_column = CustomColumns.configure :projects do |user, tag|
  columns = ModelName.method_name(user,tag)
end

@custom_column.columns should return ["title", "description"]
CustomColumns.projects.columns should return ["title", "description"]

@custom_column1 = CustomColumns.configure :groups do |domain|
  columns = ModelName.method_name(domain)
end

@custom_column1.columns should return => ["desctiption", "created_at"]
CustomColumns.groups.columns should return => ["desctiption", "created_at"]

我尝试了以下代码来实现上述结果。但是我不知道如何在块中传递不同的参数?或者我如何才能达到上述效果?

module CustomColumns
  class Rule
      attr_accessor :column_for, :columns
  end

  class << self
    attr_accessor :rule
  end

  def self.configure(column_for, &block)
    @column_for = column_for
    @columns = block.call
  end

end

1 个答案:

答案 0 :(得分:0)

你想要的是不可能的。 foo = bar 始终被解释为分配给本地变量。它永远不会调用foo= setter。您必须提供明确的接收者。