我正在开发 Railtie(gem),用于嵌入 YouTube、Vimeo 等视频。
在这个 gem 中我想要一个视图助手,这样我就可以调用 embed_video(embeddable, width, height)
所以我创建了助手作为助手,它可以工作,但我想重构它以使用部分来使其更清洁,但我发现很难做到这一点。
帮手:
module ViewHelpers
def embed_video(embeddable, width, height)
if embeddable.video_on_youtube?
content_tag :iframe, nil, width: width, height: height,
src: "//www.youtube.com/embed/#{embeddable.video_id}",
allowfullscreen: true, frameborder: 0
elsif embeddable.video_on_vimeo?
content_tag :iframe, nil, width: width, height: height,
src: "//player.vimeo.com/video/#{embeddable.video_id}",
webkitallowfullscreen: true, mozallowfullscreen: true,
allowfullscreen: true, frameborder: 0
elsif embeddable.video_on_dailymotion?
content_tag :iframe, nil, width: width, height: height,
src: "//www.dailymotion.com/embed/video/#{embeddable.video_id}",
webkitallowfullscreen: true, mozallowfullscreen: true,
allowfullscreen: true, frameborder: 0
elsif embeddable.video_on_veoh?
%Q{
<object width='#{width}' height='#{height}' id='veohFlashPlayer' name='veohFlashPlayer'>
<param name='movie' value='http://www.veoh.com/swf/webplayer/WebPlayer.swf?version=AFrontend.5.7.0.1446&permalinkId=#{embeddable.video_id}&player=videodetailsembedded&videoAutoPlay=0&id=anonymous'></param>
<param name='allowFullScreen' value='true'></param>
<param name='allowscriptaccess' value='always'></param>
<embed src='http://www.veoh.com/swf/webplayer/WebPlayer.swf?version=AFrontend.5.7.0.1446&permalinkId=#{embeddable.video_id}&player=videodetailsembedded&videoAutoPlay=0&id=anonymous' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='#{width}' height='#{height}' id='veohFlashPlayerEmbed' name='veohFlashPlayerEmbed'> </embed>
</object>
}.html_safe
#
# And more providers...
#
end
end
使用部分我想这样写:
module ViewHelpers
def embed_video(embeddable, width, height)
if embeddable.video_on_youtube?
render 'youtube', embeddable: embeddable, width: width, height: height
elsif embeddable.video_on_veoh?
render 'veoh'#...etc
end
end
end
我尝试的解决方案:
创建一个文件夹: lib/embeddable/partials
为 veoh 添加部分: lib/embeddable/partials/_veoh.html.erb
在 railtie.rb 添加视图路径
module Embeddable
class Railtie < Rails::Railtie
# ...load view helpers... #
initializer 'embeddable.add_autoload_paths', :before => :set_autoload_paths do |app|
app.config.autoload_paths << app.root.join("lib/embeddable/partials").to_s
end
# My attempt at adding the partials to the view path
initializer 'embeddable.add_view_paths', :after => :add_view_paths do |app|
ActiveSupport.on_load(:action_controller) do
append_view_path app.root.join("lib/embeddable/").to_s
end
end
end
end
当我尝试渲染视图时,出现以下错误:
ActionView::MissingTemplate: Missing partial partials/veoh with {:locale=>[:nb], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :rabl, :haml]}. Searched in:
* "/home/me/Arbeid/the_application/app/views"
* "/home/me/.rvm/gems/ruby-2.1.0/gems/kaminari-0.15.1/app/views"
* "/home/me/Arbeid/the_application/lib/embeddable"