バッチ処理でhtmlを生成したかったのですが、controllerではなく、rakeやrunnerでhtmlを出力したかったので調べました。
結論だけを書くと
# HTML生成用のクラス
class ArticleView < ActionView::Base
include Rails.application.routes.url_helpers
include ActionView::Helpers::TagHelper
def defalt_url_options
{}
end
end
def html_make
@records = Article.all # 適当にインスタンス変数を呼び出す例
action_view = ArticleView.new(Rails.root.join("app", "views"))
action_view.assign instance_variables.each_with_object({}) { |name, hash| hash[name.slice(1, name.length)] = instance_variable_get(name)} # インスタンス変数全部をレンダリングする用に渡す
action_view.render(:template => "articles/index", format: "html")
end
puts html_make
こんな感じです。
最初、参考にした[ActionView を単体で使ってみる]をそのまま使っていたのですが、
defalt_url_optionsがないとurl_forが動かなかったのでこんな感じにしてみました。
参考:
ActionView を単体で使ってみる - http://blog.eiel.info/blog/2014/07/18/action-view/
Rails 3: How to render ERb template in rake task? - Stack Overflow - http://stackoverflow.com/questions/4262044/rails-3-how-to-render-erb-template-in-rake-task