I'm kinda new to blocks, and I'm trying to create my own Rails form
builder, which I want to work like this:
form_for ... do |f|
f.form_label 'Some label' do
f.text_field :something
link_to 'somewhere', somewhere_path
end
end
In my form_label method I capture the block output and wrap some HTML
around it, but the problem is that the block only captures the last
statement, in this case, the link_to.
Here's a more clean explanation:
def dothis
yield
end
x = dothis() {
'this'
'that'
}
How do I make 'x' be an array holding both the strings. Of course I can
just make those strings into an array, but I want to do it from the
dothis method.
What do you know... After writing this, something occurred to me:
How do I make 'x' be an array holding both the strings. Of course I can
just make those strings into an array, but I want to do it from the
dothis method.
* Ivan V. <m-ruby-forum.com@omnipotente.com> (20:43) schrieb:
I'm kinda new to blocks, and I'm trying to create my own Rails form
builder, which I want to work like this:
form_for ... do |f|
f.form_label 'Some label' do
f.text_field :something
link_to 'somewhere', somewhere_path
end
end
Normally you pass that a parameter that represents the form_label, so
that the block can do something with it. Just like the form block does,
it's passed f, which represents the form.
Sorry, I seem to have mis-read your initial question. In order to do what you asked, you would have to make them an array, though (unless some of the plans for Ruby 1.9 are realized, which I sincerely hope they are not). Maybe if you give a use-case, I could be a little more helpful, though.
···
On Apr 25, 2008, at 22:54, Mikael Høilund wrote:
On Apr 25, 2008, at 20:43, Ivan V. wrote:
Here's a more clean explanation:
def dothis
yield
end
x = dothis() {
'this'
'that'
}
How do I make 'x' be an array holding both the strings. Of course I can
just make those strings into an array, but I want to do it from the
dothis method.
Sorry, I seem to have mis-read your initial question. In order to do
what you asked, you would have to make them an array, though (unless
some of the plans for Ruby 1.9 are realized, which I sincerely hope
they are not). Maybe if you give a use-case, I could be a little more
helpful, though.
Hi,
My use case is like I stated on the start of my message. I created a
function that takes a block, transforms the output of what's inside the
block, and outputs the result. I came up with something like this:
def form_label(label)
block = yield()
block = block.join("\n") if block.is_a?(Array)
"#{label}: #{block}"
end
form_label 'example' do |a|
a << text_field_tag ...
a << link_to ...
a << 'something more'
end
I didn't want to do something special inside the block (more than just
calling functions, or returning strings), as I thought "yield" would
capture everything that's inside it... which doesn't make sense once I
think more about it