How to define a method some how like the 'yield' ( I mean, automatically catch the block)? - ruby-on-rails

If I need to define a method called 'yields' which will call yiled 3 times:
def yields
3.times do
yield
end
end
And then I will use it in an other method:
def call_me_3_times
yields
end
In the console or irb:
>> call_me_3_times { puts 'me'} # => Cause error
=> LocalJumpError: no block given (yield)
from (irb):32:in `yields'
from (irb):35:in `call_me_3_times'
I hope you can read what I want;
And how to make the 'yields' autolly capture the block given?
I mean that when we use the 'yields',we don't need to pass it a '&block', just like the usage of 'yield'(we don't have to even mustn't pass the '&block' to 'yield', need we?).

Something like:
def call_me_3_times &block
yields &block
end

I tried to look at yield implementation to see if we could reproduce its behaviour, but I think it is a keyword, so there's no way to look at the implementation.
I tried with block_given, and looking at the implementation from the ruby core rdocs, I found that block_given? is implemented this way :
rb_f_block_given_p()
{
if (ruby_frame->prev && ruby_frame->prev->iter == ITER_CUR && ruby_block)
return Qtrue;
return Qfalse;
}
As you see, it's C, so it's too low-level implementation. We can't do the same.
If block_given? methods needs to rely on C implementation to just check that a block is given, I can't see how we could get that block and call it within ruby code.
So I think there's no way to do what you want.

You need given a block to you yields method or avoid yield if no block
no yield if no block :
def yields
3.times do
yield if block_given?
end
end
Pass a block to your yields methods
def call_me_3_times
yields { puts 'hello' }
end

A solution to this can be created using the techniques described in this blog post http://weblog.raganwald.com/2008/06/what-does-do-when-used-as-unary.html
def call_me_three_times
yields &(Proc.new) if block_given?
end
When you define a method as def some_method(&block) ruby will expect you to pass a block to the method. It will convert that block to a Proc and store it in the block variable.
If you prefix a Proc object with an & it will convert it to a block.
If you call Proc.new within a method and do not provide it with a block then it will create a Proc from the block passed to it.
Some test results are below
def yields
puts "Tripling"
3.times do
yield
end
end
def call_me_three_times
yields &(Proc.new) if block_given?
end
x="Foo"
call_me_three_times { puts x }
x="Bar"
call_me_three_times { puts x }
call_me_three_times
Output
Tripling
Foo
Foo
Foo
Tripling
Bar
Bar
Bar

Related

yield to an anonymous block two functions up

there is probably a simple way to do this.
I'm trying to refactor something like the following
def foo(baz)
baz.update_first
if baz.has_condition?
yield baz.val if block_given?
baz.a
else
baz.b
end
end
called like
foo(baz) {|b| b.modify}
to something like
def foo(baz)
baz.update_first
bar(baz) {|i| yield i if block_given? }
end
def bar(baz)
if baz.has_condition?
yield baz.val if block_given?
baz.a
else
baz.b
end
end
Will that work? How?
I think it will, but I'd appreciate a clear explanation of how yielding inside a block works... reading through proc.c and vm.c and a relevant git commit in the ruby source code , I think when bar is called in foo it executes until it yields, and then you walk up the frame stack to the local environment pointer for block defined in foo, which is called, where the yield walks up to the block foo is called with, executes it, and then you are back in bar. Is that correct? Is there a better way to do this?
This feels a little weird to me, like inverting control, and it requires foo to know about baz more then I'd like, but I unfortunately can't simply pass a proc or lambda in this code.
I think maybe the concept of yield will be more clear if you look at an alternative syntax, which is converting the bloc to a proc argument.
For example, the following examples are the same
def my_each(arr)
arr.each { |x| yield x }
end
def my_each(arr, &blk)
arr.each { |x| blk.call(x) }
end
# Both are called the same way
my_each([1,2,3]) { |x| print x }
# => 123
When using yield, the variable is available in the method without declaring it in the parameters list. Prepending an & sign to a parameter converts it to a proc, so in the method it can be run with .call.
Here's an example of providing a block to one method then executing it two scopes in:
def method_a(number, &blk)
method_b do
method_c do
blk.call(number)
end
end
end
def method_b(&blk)
blk.call
end
def method_c(&blk)
blk.call
end
method_a(1) { |num| puts num + 1 }
# => 2
Note that blk is not a magic word - you can name the variable whatever you want.
Here's the same thing with yield:
def method_a(number)
method_b do
method_c do
yield number
end
end
end
def method_b
yield
end
def method_c
yield
end
method_a(1) { |num| puts num + 1 }
# => 2
I think using the &blk syntax is clearer because it assigns a variable to the proc. Just because a proc is used in the method doesn't mean you have to ever run Proc.new. The block is automatically converted to a proc.

How to DRY a list of functions in ruby that are differ only by a single line of code?

I have a User model in a ROR application that has multiple methods like this
#getClient() returns an object that knows how to find certain info for a date
#processHeaders() is a function that processes output and updates some values in the database
#refreshToken() is function that is called when an error occurs when requesting data from the object returned by getClient()
def transactions_on_date(date)
if blocked?
# do something
else
begin
output = getClient().transactions(date)
processHeaders(output)
return output
rescue UnauthorizedError => ex
refresh_token()
output = getClient().transactions(date)
process_fitbit_rate_headers(output)
return output
end
end
end
def events_on_date(date)
if blocked?
# do something
else
begin
output = getClient().events(date)
processHeaders(output)
return output
rescue UnauthorizedError => ex
refresh_token()
output = getClient().events(date)
processHeaders(output)
return output
end
end
end
I have several functions in my User class that look exactly the same. The only difference among these functions is the line output = getClient().something(date). Is there a way that I can make this code look cleaner so that I do not have a repetitive list of functions.
The answer is usually passing in a block and doing it functional style:
def handle_blocking(date)
if blocked?
# do something
else
begin
output = yield(date)
processHeaders(output)
output
rescue UnauthorizedError => ex
refresh_token
output = yield(date)
process_fitbit_rate_headers(output)
output
end
end
end
Then you call it this way:
handle_blocking(date) do |date|
getClient.something(date)
end
That allows a lot of customization. The yield call executes the block of code you've supplied and passes in the date argument to it.
The process of DRYing up your code often involves looking for patterns and boiling them down to useful methods like this. Using a functional approach can keep things clean.
Yes, you can use Object#send: getClient().send(:method_name, date).
BTW, getClient is not a proper Ruby method name. It should be get_client.
How about a combination of both answers:
class User
def method_missing sym, *args
m_name = sym.to_s
if m_name.end_with? '_on_date'
prop = m_name.split('_').first.to_sym
handle_blocking(args.first) { getClient().send(prop, args.first) }
else
super(sym, *args)
end
end
def respond_to? sym, private=false
m_name.end_with?('_on_date') || super(sym, private)
end
def handle_blocking date
# see other answer
end
end
Then you can call "transaction_on_date", "events_on_date", "foo_on_date" and it would work.

Is there a way to access method arguments in Ruby?

New to Ruby and ROR and loving it each day, so here is my question since I have not idea how to google it (and I have tried :) )
we have method
def foo(first_name, last_name, age, sex, is_plumber)
# some code
# error happens here
logger.error "Method has failed, here are all method arguments #{SOMETHING}"
end
So what I am looking for way to get all arguments passed to method, without listing each one. Since this is Ruby I assume there is a way :) if it was java I would just list them :)
Output would be:
Method has failed, here are all method arguments {"Mario", "Super", 40, true, true}
In Ruby 1.9.2 and later you can use the parameters method on a method to get the list of parameters for that method. This will return a list of pairs indicating the name of the parameter and whether it is required.
e.g.
If you do
def foo(x, y)
end
then
method(:foo).parameters # => [[:req, :x], [:req, :y]]
You can use the special variable __method__ to get the name of the current method. So within a method the names of its parameters can be obtained via
args = method(__method__).parameters.map { |arg| arg[1].to_s }
You could then display the name and value of each parameter with
logger.error "Method failed with " + args.map { |arg| "#{arg} = #{eval arg}" }.join(', ')
Note: since this answer was originally written, in current versions of Ruby eval can no longer be called with a symbol. To address this, an explicit to_s has been added when building the list of parameter names i.e. parameters.map { |arg| arg[1].to_s }
Since Ruby 2.1 you can use binding.local_variable_get to read value of any local variable, including method parameters (arguments). Thanks to that you can improve the accepted answer to avoid evil eval.
def foo(x, y)
method(__method__).parameters.map do |_, name|
binding.local_variable_get(name)
end
end
foo(1, 2) # => 1, 2
One way to handle this is:
def foo(*args)
first_name, last_name, age, sex, is_plumber = *args
# some code
# error happens here
logger.error "Method has failed, here are all method arguments #{args.inspect}"
end
This is an interesting question. Maybe using local_variables? But there must be a way other than using eval. I'm looking in Kernel doc
class Test
def method(first, last)
local_variables.each do |var|
puts eval var.to_s
end
end
end
Test.new().method("aaa", 1) # outputs "aaa", 1
If you need arguments as a Hash, and you don't want to pollute method's body with tricky extraction of parameters, use this:
def mymethod(firstarg, kw_arg1:, kw_arg2: :default)
args = MethodArguments.(binding) # All arguments are in `args` hash now
...
end
Just add this class to your project:
class MethodArguments
def self.call(ext_binding)
raise ArgumentError, "Binding expected, #{ext_binding.class.name} given" unless ext_binding.is_a?(Binding)
method_name = ext_binding.eval("__method__")
ext_binding.receiver.method(method_name).parameters.map do |_, name|
[name, ext_binding.local_variable_get(name)]
end.to_h
end
end
This may be helpful...
def foo(x, y)
args(binding)
end
def args(callers_binding)
callers_name = caller[0][/`.*'/][1..-2]
parameters = method(callers_name).parameters
parameters.map { |_, arg_name|
callers_binding.local_variable_get(arg_name)
}
end
You can define a constant such as:
ARGS_TO_HASH = "method(__method__).parameters.map { |arg| arg[1].to_s }.map { |arg| { arg.to_sym => eval(arg) } }.reduce Hash.new, :merge"
And use it in your code like:
args = eval(ARGS_TO_HASH)
another_method_that_takes_the_same_arguments(**args)
If the function is inside some class then you can do something like this:
class Car
def drive(speed)
end
end
car = Car.new
method = car.method(:drive)
p method.parameters #=> [[:req, :speed]]
If you would change the method signature, you can do something like this:
def foo(*args)
# some code
# error happens here
logger.error "Method has failed, here are all method arguments #{args}"
end
Or:
def foo(opts={})
# some code
# error happens here
logger.error "Method has failed, here are all method arguments #{opts.values}"
end
In this case, interpolated args or opts.values will be an array, but you can join if on comma. Cheers
It seems like what this question is trying to accomplish could be done with a gem I just released, https://github.com/ericbeland/exception_details. It will list local variables and vlaues (and instance variables) from rescued exceptions. Might be worth a look...
Before I go further, you're passing too many arguments into foo. It looks like all of those arguments are attributes on a Model, correct? You should really be passing the object itself. End of speech.
You could use a "splat" argument. It shoves everything into an array. It would look like:
def foo(*bar)
...
log.error "Error with arguments #{bar.joins(', ')}"
end

Explain Iterator Syntax on Ruby on Rails

I started learning Ruby on Rails and found myself confounded by the syntax, so I had to read about somet of the Ruby syntax. I learned the syntax from http://www.cs.auckland.ac.nz/references/ruby/doc_bundle/Manual/man-1.4/syntax.html:
method_call do [`|' expr...`|'] expr...end
They call it an Iterator. I understand an iterator runs through a loop, but I don't understand how exactly I'm supposed to read this or what's going on in in this syntax. I see it all the time in RoR screencasts and the words make sense, but I actually have no idea what's going on. Could anyone explain this to me?
edit: example
respond_to do |format|
format.json
format.xml { render :xml => #posts }
end
Methods can take a construct called "Blocks". These are anonymous methods that get passed into the method.
Another syntax for this is:
method_call { |var| do_something(var) }
Basically, you are saying that for each item in an iteration, name it "var" and do something with that item. The method simply calls your block that you passed in as it "yields" items to it.
Does this help?
edit: In your example, you they are using the iterator pattern in a funny way... probably only passing one format object into your block, so you can then tell it which formats to handle, and what to do when you see it.
In other words, they are using the pattern to create a DSL of sorts that lets you configure what you respond to.
In the case of iterators, think of them like an interface in Java: you can do a for-loop in Ruby, but all the objects that you might want to iterate over (should) implement the 'each' method which takes a block (i.e. a closure, an anonymous function).
Blocks are used all over the place in Ruby. Imagine you have this array:
[1, 2, 3, 4, 5, 6].each do |i| puts i.to_s end
Here, you are creating the array and then you are calling the 'each' method on it. You pass the block to it. You could separate this out, like this:
arr = [1, 2, 3, 4, 5, 6]
string_printer = lambda do |i| puts i.to_s end
arr.each(&string_printer)
This kind of interface is implemented in other things: the Hash collection lets you iterate over the key-value pairs:
{:name => "Tom", :gender => :male}.each do |key, value| puts key end
The do..end can be replaced with braces, like this:
[1, 2, 3, 4, 5, 6].each {|i| puts i.to_s }
This kind of iteration is made possible because of the functional-programming that Ruby employs: if you are creating a class that needs to iterate over something, you can also implement the each method. Consider:
class AddressBook
attr_accessor :addresses
def each(&block)
#addresses.each {|i| yield i }
end
end
All sorts of classes implement interesting functionality through this block pattern: look at String's each_line and each_byte method, for instance.
method_call do [`|' expr...`|'] expr...end
Is not limited to iteration functions.
In ruby, any method can take a block as an argument. The block can then be called by the method. In the case of an iterator, the method looks something like this:
def iter
for i in [:x,:y,:z]
yield i
end
end
If you call iter with a block, it will loop over [:x, :y, :z] and yield each of them to the block, which can then do whatever you want. e.g. to print them out:
iter { |z| puts z }
You can also use this to hide init and cleanup steps, like opening and closing files. e.g. File.open. File.open, if it were implemented in pure ruby(it's in C for performance) would do something like this.
def File.open filename, opts
f = File.new filename, opts
yield f
f.close
end
Which is why you can use
File.open 'foobar', 'w' do |f|
f.write 'awesome'
end
respond_to is similar. It works something like this:( check out the real implementation here)
def respond_to
responder = Responder.new(self)
block.call(responder)
responder.respond
end
It creates a responder object that has methods like html that take a block and passes it to you. This turns out to be really handy, because it lets you do things like:
def action
#foo = Foo.new params[:foo]
respond_to do |format|
if #foo.save
format.html { redirect_to foo_path #foo }
format.xml { render :xml => #foo.to_xml }
else
flash[:error] = "Foo could not be saved!"
format.html { render :new }
format.xml { render :xml => {:errors => #foo.errors }.to_xml}
end
end
end
See how I change the behavior dependent on save inside the block? Doing this would be much more annoying without it.
<function> do |<temp variable>|
<code to operate on temp variable>
end
This creates a temporary anonymous function which accepts an item into a temporary variable, and then lets things operate on that item. The anonymous function is passed in to the original <function> specified to operate on the items yielded by that function.
What you see there is a block of code, the syntax is a bit awkward when you first see it.
So, basically, with iterators your have a "thing" that may be repeated, and it receives a block to know what to do.
For instance the Range class has a method called "each" which receives the block of code to execute on each element in the range.
Let's say you want to print it:
range = 1..10 #range literal
range.each {|i|
puts i
}
The code: {|i| puts i} is a block that says what to do when this range iterates over each one of its elements. The alternate syntax is the one you posted:
range.each do |i|
puts i
end
These blocks are used with iterators, but they are not limited to "iteration" code, you can use them in other scenarios, for instance:
class Person
def initialize( with_name )
#name = with_name
end
# executes a block
def greet
yield #name #passes private attribute name to the block
end
end
p = Person.new "Oscar"
p.greet { |n|
puts "Name length = #{n.length}"
puts "Hello, #{n}"
}
Prints:
Name length = 5
Hello, Oscar
So, instead of having a greet method with a fixed behavior, using block let the developer specify what to do, which is very helpful with iterators, but as you have just witness not the only place. In your case, that block is letting you specify what to do in the respond_to method.
The documentation you are reading is ancient -- practically prehistoric. If it were possible for web pages to gather dust, that one would have a thick layer.
Try the reference material at the ruby-lang website. Also, the Programming Ruby (pickaxe) book is an essential reference.
I think you could call it iterator, because often, the block function is called more than once. As in:
5.times do |i|
puts "#{i} "
end
"Behind the scenes", the following steps are made:
The method times of the object instance 5 is called, passing the code puts "#{i} " in a Proc object instance.
Inside the times method, this code is called inside a loop, passing the current index as a parameter. That's what times could look like (it's in C, actually):
class Fixnum
def times_2(&block) # Specifying &block as a parameter is optional
return self unless block_given?
i = 0
while(i < self) do
yield i # Here the proc instance "block" is called
i += 1
end
return self
end
end
Note that the scope (i.e. local variables etc.) is copied into the block function:
x = ' '
5.times do { |i| puts "#{i}" + x }

Writing an around_each filter in ruby for every method within a block.

I need a method that takes a block, and performs something similar to an around_each filter for every method within the block.
For instance:
def method_that_takes_block
(#threads ||= Array.new) << Thread.new {yield if block.given?}
end
method_that_takes_a_block do
method_one
method_two
method_three
end
In this instance I would like my method that takes a block to Thread each method within the block and pushes that thread to the #threads array. Essentially I'm just looking for a DRY way to wrap a thread around every method called within a block.
You can't directly wrap a thread around each statement in the block body, if they can be arbitrary statements; there's no way to get that sort of control over the execution of a block body in Ruby. If you can restrict what goes in the block body, you have some more flexibility.
If each of the statements you are executing is simply a method call, as you imply in your example, you can use instance_exec to execute that block on a proxy object, which uses method_missing to spawn a new thread and then forward the method call on to the real object (or do whatever wrapper you're interested in; for the sake of example, I'll just wrap with some print statements):
class Proxy
def initialize obj
#obj = obj
end
def method_missing method, *args
puts "<wrapper>"
#obj.send method, *args
puts "</wrapper>"
end
end
class MethodWrapper
def tell_me_a_joke
puts "Knock, knock?"
end
def whos_there
puts "Orange"
end
def orange_who
puts "Orange you glad I didnt say banana?"
end
def wrap_around &blk
Proxy.new(self).instance_exec &blk
end
end
And here's how you can use it:
>> MethodWrapper.new.wrap_around { tell_me_a_joke; whos_there; orange_who }
<wrapper>
Knock, knock?
</wrapper>
<wrapper>
Orange
</wrapper>
<wrapper>
Orange you glad I didnt say banana?
</wrapper>
=> nil
The previous follows the pattern that you gave in your question, but it's less than ideal as only methods that are forwarded to the underlying object get wrapped:
>> MethodWrapper.new.wrap_around { tell_me_a_joke; puts "something" }
<wrapper>
Knock, knock?
</wrapper>
something
=> nil
You could instead just use instance_exec directly, and call the a wrapper method that takes a block, to get almost the same effect, though slightly less DRY as you need to call your wrapper method each time:
class SimpleWrapper
def tell_me_a_joke
puts "Knock, knock?"
end
def whos_there
puts "Interrupting cow"
end
def interrupting_co
puts "Moooooo!"
end
def wrap
puts "<wrap>"
yield
puts "</wrap>"
end
end
And in use:
>> SimpleWrapper.new.instance_exec do
wrap { tell_me_a_joke }
wrap { whos_there }
wrap { interrupting_co }
wrap { puts "Something" }
end
<wrap>
Knock, knock?
</wrap>
<wrap>
Interrupting cow
</wrap>
<wrap>
Moooooo!
</wrap>
<wrap>
Something
</wrap>
=> nil
You can also do it like this:
%w(method_one method_two method_three).each do |method|
(#threads ||= Array.new) << Thread.new { self.send(method) }
end

Resources