Dynamic partial name for an object

南楼画角 提交于 2019-12-13 03:57:21

问题


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_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>

回答1:


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.




回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/6733549/dynamic-partial-name-for-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!