在ruby中编写一个DSL方法,该方法将创建一个带参数的方法

时间:2022-04-27 23:17:41

I'm attempting to write a DSL for a background worker class, and I'm a little stuck trying to accomplish something.

我正在为一个后台工人类编写一个DSL,但是我在尝试完成一些事情时遇到了一些困难。

Ideally, I should be able to write a job worker like the following...

理想情况下,我应该能够写出如下这样的工作内容……

job :job_name do |param1, param2|
  puts param1
end

Now, in my worker superclass class, I'm doing something like this...

现在,在我的工人超课上,我正在做这样的事情……

class Worker
  def self.job(job_name, &block)
    define_method job_name do
      # stuck
    end
    # do some additional stuff here
  end
end

What I want to do is define a method that has access to the block arguments that were used in the original job call, so I could fire this job off with:

我想要做的是定义一个方法,该方法可以访问原始作业调用中使用的块参数,因此我可以用:

Worker.new.job_name(param1, param2)

The method created should be functionally equivalent to:

所创建的方法在功能上应相当于:

def job_name(param1, param2)
  puts param1
end

Does that make any sense? Hoping someone here can point me in the right direction.

这说得通吗?希望有人能给我指明正确的方向。

2 个解决方案

#1


5  

Do you look for something like this:

你会找这样的东西吗?

class Worker
  def self.job(job_name, &block)
    define_method job_name, &block
    # do some additional stuff here
  end
end

Worker.job(:my_job) do |a,b| 
  puts "Called #{__method__} with param <#{a}> and <#{b}>"
end

#~ What I want to do is define a method that has access to the block arguments that were used in the original job call, so I could fire this job off with:
Worker.new.my_job(:param1,:param2) #-> Called my_job with param <param1> and <param2>

#2


1  

Something like this?

是这样的吗?

class Worker
  def self.job(job_name, &block)
    define_method job_name, block
  end
end

Worker.job("foo"){ |x,y| puts "#{x} + #{y}" }
Worker.new.foo(1,2) # => 1 + 2

#1


5  

Do you look for something like this:

你会找这样的东西吗?

class Worker
  def self.job(job_name, &block)
    define_method job_name, &block
    # do some additional stuff here
  end
end

Worker.job(:my_job) do |a,b| 
  puts "Called #{__method__} with param <#{a}> and <#{b}>"
end

#~ What I want to do is define a method that has access to the block arguments that were used in the original job call, so I could fire this job off with:
Worker.new.my_job(:param1,:param2) #-> Called my_job with param <param1> and <param2>

#2


1  

Something like this?

是这样的吗?

class Worker
  def self.job(job_name, &block)
    define_method job_name, block
  end
end

Worker.job("foo"){ |x,y| puts "#{x} + #{y}" }
Worker.new.foo(1,2) # => 1 + 2

相关文章