Module: ResponsiveImages::ViewHelpers

Defined in:
lib/responsive_images/view_helpers.rb

Instance Method Summary collapse

Instance Method Details

#alternative_sizes(image, sizes) ⇒ Object

Loop over the images sizes and create our data attributes hash



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/responsive_images/view_helpers.rb', line 47

def alternative_sizes image, sizes
  data_sizes = {}
  sizes[:sizes].each do |size, value|
    if value.present?
      data_sizes["data-#{size}-src"] = (value == :default ? image.url : image.send(value))
    else
      false
    end
  end
  data_sizes
end

#device_typeObject

Use mobvious to get the user’s device type, it will return mobile, tablet or desktop



6
7
8
# File 'lib/responsive_images/view_helpers.rb', line 6

def device_type
  return request.env['mobvious.device_type']
end

#responsive_background_image(image, options = {}) ⇒ Object



24
25
26
27
28
# File 'lib/responsive_images/view_helpers.rb', line 24

def responsive_background_image image, options={}
  # Merge any options passed with the configured options
  sizes = ResponsiveImages.options.deep_merge(options)
  data_hash = { style: "background-image: url(#{src_path(image, sizes)})" }.merge(alternative_sizes(image, sizes))      
end

#responsive_image_tag(image, options = {}) ⇒ Object

Create a image tag with our responsive image data attributes



12
13
14
15
16
17
18
19
20
21
# File 'lib/responsive_images/view_helpers.rb', line 12

def responsive_image_tag image, options={}
  # Merge any options passed with the configured options
  sizes = ResponsiveImages.options.deep_merge(options)  
  # Let's create a hash of the alternative options for our data attributes    
  data_sizes = alternative_sizes(image, sizes)
  # Get the image source
  image_src = src_path(image, sizes)      
  # Return the image tag with our responsive data attributes
  return image_tag image_src, data_sizes.merge(options)
end

#src_path(image, sizes) ⇒ Object

Let’s identify the default image size for the image tag. If it’s a desktop then our default src attribute should be desktop (or default) but if it’s a mobile or table then we should set the src attribute to the mobile or tablet image



34
35
36
37
38
39
40
41
42
43
# File 'lib/responsive_images/view_helpers.rb', line 34

def src_path image, sizes
  case device_type
  when :desktop
    image_src = sizes[:default] == :default ? image.url : image.send(sizes[:default])
  when :tablet
    image_src = sizes[:sizes][:tablet].present? ? image.send(sizes[:sizes][:tablet]) : image.send(sizes[:default])
  when :mobile
    image_src = sizes[:sizes][:mobile].present? ? image.send(sizes[:sizes][:mobile]) : image.send(sizes[:default])
  end
end