我有這樣的代碼在我的控制器:軌最好的方式來抽象深對象文本數據
def home
@mainImage = []
@mainImage.push(
{:breakpoint => 1024,
:src => i_path('pages/home-d.jpg'),
:src_2x => i_path('pages/home-d_2x.jpg')}
)
@mainImage.push(
{:breakpoint => 768,
:src => i_path('pages/home-t.jpg'),
:src_2x => i_path('pages/home-t_2x.jpg')}
)
@mainImage.push(
{:breakpoint => 320,
:src => i_path('pages/home-m.jpg'),
:src_2x => i_path('pages/home-m_2x.jpg')}
)
@alt = 'An image description'
@defaultImage = i_path('pages/home-m.jpg')
end
其中在視圖顯示了部分的幫助。
我現在需要添加類似的功能來從回形針對象渲染模型屬性。
這是現在看起來像這樣:
@respImage.push(
{:breakpoint => 1024,
:src => slide.image.url(:desktop_reg),
:src_2x => slide.image.url(:desktop_retina)}
)
@respImage.push(
{:breakpoint => 768,
:src => slide.image.url(:tablet_reg),
:src_2x => slide.image.url(:tablet_retina)}
)
#...
是最終目標有一個幻燈片,有許多幻燈片。 幻燈片有幾個屬性字符串和一個回形針屬性。 回形針屬性對於每個圖像大小都有6種樣式。
Rails如何將上述數據傳輸到視圖中的標準機制是什麼? 我假設這個通用數組不是最靈活的解決方案。
這是代碼結束的地方。
在控制器:
def home
@mainImage2 = RespImage.new(:alt => 'default homepage image')
@mainImage2.add_breakpoint(BREAKPOINTS['desktop'],i_path('pages/home-d.jpg'),i_path('pages/home-d_2x.jpg'));
@mainImage2.add_breakpoint(BREAKPOINTS['tablet'],i_path('pages/home-t.jpg'),i_path('pages/home-t_2x.jpg'));
#...
模型/ resp_image.rb:
class RespImage
attr_accessor :alt, :breakpoints
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def add_breakpoint(px,src,src_2x)
self.breakpoints ||= [];
self.breakpoints.push RespBreakpoint.new(:px => px, :src => src, :src_2x =>src_2x)
end
def add_paperclip_breakpoints(paperclip)
add_breakpoint(BREAKPOINTS('desktop'), paperclip.url(:desktop_reg), paperclip.url(:desktop_retina));
add_breakpoint(BREAKPOINTS('tablet'), paperclip.url(:tablet_reg), paperclip.url(:tablet_retina));
add_breakpoint(BREAKPOINTS('mobile'), paperclip.url(:mobile_reg), paperclip.url(:mobile_retina));
end
def default_src
self.breakpoints.sort.first.src
end
end
模型/ resp_breakpoint
class RespBreakpoint
include Comparable
attr_accessor :px,:src,:src_2x
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def better_than?(other)
self.px > other.px
end
def <=>(other)
self.px <=> other.px
end
def eql?(other)
self.px === other.px
end
end
非常感謝@Dave Newton以下。
我已經添加了更多的細節問題。 – LessQuesar
神聖煙,你幫了很多。非常感謝您的寶貴時間。我對代碼感到非常滿意,我會在上面貼上後代。順便說一下,視圖不需要區分3個斷點,所以我忽略了斷點的散列。像素值本身是輸出環路中唯一需要的差異。我使用響應式圖像JS polyfill是確切的。 – LessQuesar