Module: Mobvious::Rails::Helper

Defined in:
lib/mobvious/rails/helper.rb

Overview

A module holding Rails view helper extensions.

Just put include Mobvious::Rails::Helper into your ApplicationHelper.

Instance Method Summary collapse

Instance Method Details

#device_typeSymbol

Returns device type for current request.

Returns:

  • (Symbol)

    device type for current request



36
37
38
# File 'lib/mobvious/rails/helper.rb', line 36

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

#for_device_type(*wanted_device_types) { ... } ⇒ Object

Executes a block of code only when a request was made by a given client device type.

Example:

<% for_device_type :mobile do %>
  <p>This gets rendered only on mobile phones.</p>
<% end %>

Parameters:

  • wanted_device_type

    a symbol identifying a device type

Yields:

  • a block to execute if the specified device type matches device type of the current request

Returns:

  • value that the yielded block returns, or nil if it didn't get executed



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mobvious/rails/helper.rb', line 19

def for_device_type(*wanted_device_types)
  unless block_given?
    raise ArgumentError, "Device helper takes a block of content to render for given device."
  end

  unless device_type
    raise "Mobvious device type not set. Did you add the Mobvious rack middleware?"
  end

  if wanted_device_types.include? device_type
    yield
  else
    nil
  end
end

#mobvious_javascriptString

Forms a <script> tag setting JavaScript variable window.Mobvious.device_type to a string holding current request's device type. You can then use Mobvious.device_type in all your JavaScripts to get this value.

Example:

<head>
  <%= mobvious_javascript %>

  <script type="text/javascript">
    alert(Mobvious.device_type); // this will print 'mobile' or 'desktop' or similar
  </script>
</head>

Returns:

  • (String)

    script tag that sets Mobvious variables (returned string is html_safe)



55
56
57
58
59
60
61
62
63
64
# File 'lib/mobvious/rails/helper.rb', line 55

def mobvious_javascript
  "<script type=\"text/javascript\">\nif (window.Mobvious === undefined) {\nwindow.Mobvious = {};\n}\nwindow.Mobvious.device_type = '\#{device_type.to_s}';\n</script>\n".html_safe
end