Topic: Using Helper Methods Outside View?

Ok, I'd like to use some of the helper methods in a migration, (dont ask).  Does anyone know how I would go about that?

I tried including TextHelper

class AutoFormatBlog < ActiveRecord::Migration
  include ActionView::Helpers::TextHelper

  def self.up
    entries = Entry.find(:all)
    for entry in entries
      entry.content = simple_format(entry.content)
    end
  end

Re: Using Helper Methods Outside View?

Including the module doesn't work? Are you getting an error message or something? Sorry, I'm too lazy to test it.

Edit: Oh, simple_format method uses the content_tag method found in ActionView::Helpers::TagHelper, so try including that too.

Last edited by ryanb (2006-07-31 13:55:33)

Railscasts - Free Ruby on Rails Screencasts

Re: Using Helper Methods Outside View?

If you're dealing with formatting the entry content I'd put that code in the model.

[code lang=ruby]
class Entry < ActiveRecord::Base
  def simplify_content!
    content = simple_format(entry.content)
  end
end
[/code]

But either way you'll have to get over the hurdle of having the simple_format method available.  I think all you need in addition to the text_helper is the tag_helper:
[code lang=ruby]
include ActionView::Helpers::TextHelper
include ActionView::Helpers::TagHelper
def self.up
  entries = Entry.find(:all)
  for entry in entries
    entry.content = simple_format(entry.content)
  end
end
[/code]

Re: Using Helper Methods Outside View?

Ooh, Ryan.  You beat me fair and square.

Re: Using Helper Methods Outside View?

Sorry, it's saying it can't find simple_format.  I'll try including tag_helper.

Danger, this is a one time conversion.  Basically I was using simple format, but now I'm adding a wysiwyg tool.  So now I have to convert all the old entries to html in the database.

Thanks.

Re: Using Helper Methods Outside View?

I added TagHelper, still

undefined method `simple_format' for #<ActiveRecord::ConnectionAdapters::MysqlAdapter:0x3781ccc>

Re: Using Helper Methods Outside View?

Ahha, you are attempting to call an instance method from inside a class method. Try extending the module instead of including it. I believe this will make the methods in the module class methods. I have no clue how well this will work though.

extend ActionView::Helpers::TagHelper
extend ActionView::Helpers::TextHelper

Railscasts - Free Ruby on Rails Screencasts

Re: Using Helper Methods Outside View?

That worked ryan, thanks dude.

Though it makes my very uncomfortable, thinking about the extend keyword in Java.  I'll just have to get over it.