开发者

Dynamic partial name for an object

render @some_object

will render Rails.root/app/views/some_objects/_some_object.html.erb

Now I want to handle which partial will be rendered depends on its data_type field. For example:

class SomeObject < AR::Base
  # some magick method wich I need to rewrite
  def partial_name
    case data_type
    when "String"
      "string_template"
    when "Text"
      "text_template"
    else
      "blank_template"
    end
  end
end

I know there is model开发者_StackOverflow社区_name, i18n_key and some others, which are returnes model name, but which one is used in my render @object case?

EDIT

Now I've stopped on the easiest solution that didn't touch models. I removed all this logic into _some_object.html.erb partial, so it renders partial I need inside of itself:

<div class='claim_template_field'>
  <%= render "/some_objects/#{f.object.data_type.downcase}_template", :f => f %>
</div>


If you have a limit set of values for the data_type field you could create subclasses from SomeObject, one for each data_type.

class SomeObject < AR::Base
  inheritance_column :data_type
end

Then you could create a default partial for each subclass.

This isn't exactly a "dynamic" solution, but I thought I'd throw it out as a suggestion.


actionpack/lib/view/action_view/render/partials.rb defines a method for determining the partial path for objects:

      def partial_path(object = @object)
        @partial_names[object.class.name] ||= begin
          object = object.to_model if object.respond_to?(:to_model)

          object.class.model_name.partial_path.dup.tap do |partial|
            path = @view.controller_path
            partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/)
          end
        end
      end

You will probably need to define model_name to return a String that has the partial_path method defined.


Now I've stopped on the easiest solution that didn't touch models. I removed all this logic into _some_object.html.erb partial, so it renders partial I need inside of itself:

<div class='claim_template_field'>
  <%= render "/some_objects/#{f.object.data_type.downcase}_template", :f => f %>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜