小编Bre*_*chi的帖子

在ruby中调用模型中的方法之前

这是我的实现,以开发方式在模型中的所有方法之前运行代码

调用"before_hook:months_used"方法需要在类的底部到ExecutionHooks才能获得在模块中加载的instance_method.我想在顶部加载实例方法

class BalanceChart < BalanceFind
 include ExecutionHooks

 attr_reader :options

 def initialize(options = {})
  @options = options
  @begin_at = @options[:begin_at]
 end

 def months_used
  range.map{|date| I18n.l date, format: :month_year}.uniq!
 end

 before_hook :months_used
end

module ExecutionHooks

def self.included(base)
 base.send :extend, ClassMethods
end

module ClassMethods
  def before
   @hooks.each do |name|
    m = instance_method(name)
    define_method(name) do |*args, &block|  

      return if @begin_at.blank? ## the code you can execute before methods

      m.bind(self).(*args, &block) ## your old code in the method of the class
    end
   end
  end …
Run Code Online (Sandbox Code Playgroud)

ruby model metaprogramming

7
推荐指数
1
解决办法
2960
查看次数

如何使用哈希除了数组值?或者如何创建哈希线?

尝试使用Hash,除了代码中的许多值

H1 =哈希[:state => 1,代码=> 2]

H2 = Hash [:state => 10,code => 20]

这项工作:

H1.except(:state, :code)
Run Code Online (Sandbox Code Playgroud)

哈希 - > H1不包含值.好

但是波纹管不起作用

H1.expect(H2.keys)
Run Code Online (Sandbox Code Playgroud)

哈希 - > H1将包含值.不

问题是因为ruby将order.keys与BRACKET放在一起.我试图从数组生成但也无法工作

ruby arrays hash

3
推荐指数
1
解决办法
1538
查看次数

标签 统计

ruby ×2

arrays ×1

hash ×1

metaprogramming ×1

model ×1