Module: Espresso::View::InstanceMethods

Includes:
WillPaginate::ViewHelpers
Defined in:
lib/espresso/view.rb,
lib/espresso/view/has_scope.rb,
lib/espresso/view/searchlogic.rb,
lib/espresso/view/will_paginate.rb,
lib/espresso/view/inherited_resources.rb

Constant Summary collapse

VIEW_PLACEHOLDERS =
{
  'create' => 'new',
  'update' => 'edit'
}

Instance Method Summary collapse

Instance Method Details

#body_modifiersObject

Make body’s modifiers, based on controller_name and action_name



239
240
241
# File 'lib/espresso/view.rb', line 239

def body_modifiers
  {:class => "m-#{controller_name} m-#{controller_name}_#{action_name}"}
end

#date(time_or_date, options = {}) ⇒ String

Helper to write date in human- and machine-readable format

Parameters:

  • time_or_date (Time, DateTime, Date)

    time or date to represent

Returns:

  • (String)

    <time> tag with time or date to represent



75
76
77
# File 'lib/espresso/view.rb', line 75

def date(time_or_date, options = {})
  time(time_or_date.to_date, options)
end

#default_page_titleString

Makes default page title, based on controller and action

Returns:

  • (String)

    default page title



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/espresso/view.rb', line 110

def default_page_title
  text = case view_name
         when 'index'
           if collection?
             resource_class.name
           else
             controller_name.camelize
           end
         when 'new'
           "#{t('espresso.navigation.new', :default => 'New')} #{(resource? ? resource_class : controller_name.classify.constantize).human_name}"
         when 'edit'
           "#{t('espresso.navigation.edit', :default => 'Edit')} #{(resource? ? resource_class : controller_name.classify.constantize).human_name}"
         else
           t("navigation.#{controller_name}.#{view_name}")
         end
  %(<span class="translation_missing">#{text}</span>)
end

#head_title(default = false, separator = ' | ') ⇒ Object



162
163
164
165
# File 'lib/espresso/view.rb', line 162

def head_title(default = false, separator = ' | ')
  default ||= t('application.meta.title')
  [page_title(nil, true), default].compact.join(separator)
end


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/espresso/view/inherited_resources.rb', line 45

def link_to_destroy(object=nil, path=nil)
  object ||= resource
  path ||= if object == resource
             resource_path
           else
             object
           end
  class_underscored = object.class.name.underscore
  link_to(t("helpers.action.#{class_underscored}.edit",
            :default => [:'helpers.action.destroy', 'Destroy']),
          path,
          :class => Espresso::View.block_classes('action', %w(destroy)),
          :method => :delete,
          :confirm => t("helpers.action.#{class_underscored}.confirm_destroy",
                        :default => [:'helpers.action.confirm_destroy', 'are you sure?']))
end


31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/espresso/view/inherited_resources.rb', line 31

def link_to_edit(object=nil, path=nil)
  object ||= resource
  path ||= if object == resource
             edit_resource_path
           else
             [:edit, object]
           end
  link_to(t("helpers.action.#{object.class.name.underscore}.edit",
            :default => [:'helpers.action.edit', 'Edit']),
          path,
          :class => Espresso::View.block_classes('action', %w(edit)))
rescue
end


62
63
64
65
66
67
68
# File 'lib/espresso/view/inherited_resources.rb', line 62

def link_to_index
  link_to(t("helpers.action.#{controller_name.singularize}.index",
            :default => [:'helpers.action.index', '&larr; Back']),
              collection_path,
              :class => 'b-action b-action_index')
rescue
end


7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/espresso/view/inherited_resources.rb', line 7

def link_to_new(klass=nil, path=nil)
  klass ||= resource_class
  klass_underscored = klass.name.underscore
  path ||= if klass == resource_class
             new_resource_path
           else
             [:new, klass_underscored]
           end
  link_to(t("helpers.action.#{klass_underscored}.new",
            :default => [:'helpers.action.new', 'Add']),
          path,
          :class => Espresso::View.block_classes('action', %w(new)))
rescue
end


22
23
24
25
26
27
28
29
# File 'lib/espresso/view/inherited_resources.rb', line 22

def link_to_show(object=nil)
  object ||= resource
  link_to(t("helpers.action.#{object.class.name.underscore}.show",
            :default => [:'helpers.action.show', object.to_s]),
          object,
          :class => Espresso::View.block_classes('action', %w(show)))
rescue
end

#model_classes(model) ⇒ Object

Model‘s classes, based on Model.model_modifiers

Parameters:



83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/espresso/view.rb', line 83

def model_classes(model)
  klass = model.class
  main_class = klass.name.underscore.gsub(/(_|\/)/, '-')
  modifiers = if klass.respond_to?(:model_modifiers)
                klass.model_modifiers.find_all do |modifier|
                  method = "#{modifier}?"
                  model.respond_to?(method) && model.send(method)
                end
              else
                []
              end
  Espresso::View.block_classes(main_class,
                                    modifiers)
end

Draws navigation list, using <li> with <a>

Parameters:

  • menu (Array<Symbol, String>)

    list of menu items (paths without /)

Returns:

  • (String)

    Resulting menu without <ul> or <ol>



170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/espresso/view.rb', line 170

def navigation_list(menu)
  ''.tap do |result|
    menu.each do |item|
      path = "/#{item}"
      uri = request.request_uri
      title = t("navigation.#{item}.index", :default => item.to_s.camelize)
      result << (:li, :class => uri.starts_with?(path) ? 'selected' : nil) do
        link_to_unless_current(title, path) {
          (:strong, title)
        }
      end
    end
  end
end

#online_stats(options = {}) ⇒ Object

Set online statistics trackers

Parameters:

  • options (Hash) (defaults to: {})

    online statistics keys

Options Hash (options):

  • :piwik (Hash)

    Piwik code: id. site

  • :metrika (String, Numeric)

    Yandex.Metrika code

  • :analytics, (String)


190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/espresso/view.rb', line 190

def online_stats(options = {})
  static_includes = []
  dynamic_includes = ''
  noscript_includes = []
  initializers = []

  if piwik = options.delete(:piwik)
    static_includes   << "//#{piwik[:site]}/piwik.js"
    initializers      << "var piwikTracker=Piwik.getTracker('//#{piwik[:site]}/piwik.php',#{piwik[:id]});piwikTracker.trackPageView();piwikTracker.enableLinkTracking();"
    noscript_includes << "//#{piwik[:site]}/piwik.php?idsite=#{piwik[:id]}"
  end

  if metrika = options.delete(:metrika)
    static_includes   << '//mc.yandex.ru/resource/watch.js'
    initializers      << "var yaCounter#{metrika}=new Ya.Metrika(#{metrika});"
    noscript_includes << "//mc.yandex.ru/watch/#{metrika}"
  end

  if analytics = options.delete(:analytics)
    dynamic_includes << 'var gaJsHost=("https:"==document.location.protocol)?"https://ssl.":"http://www.";'
    dynamic_includes << 'document.write(unescape("%3Cscript src=\'"+gaJsHost+"google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3Ei"));'
    initializers     << "var pageTracker=_gat._getTracker('#{analytics}');pageTracker._trackPageview();"
  end

  ''.tap do |result|
    unless dynamic_includes.empty?
      result << javascript_tag(dynamic_includes)
    end
    result << javascript_include_tag(static_includes) unless static_includes.empty?
    unless initializers.empty?
      initializers = initializers.collect do |initializer|
                                                                                                                                      "try {#{initializer}} catch(e) {}"
      end.join("\n")
      result << javascript_tag(initializers)
    end

    unless noscript_includes.empty?
      includes = noscript_includes.collect do |noscript|
                                                                                                                                                %(<img src="#{noscript}" style="border:0" alt="" />)
      end.join("\n")
      result << (:noscript,
                            (:div,
                                        includes,
                                        :style => 'position: absolute'))
    end
  end
end

#overwrite_path(overwrites, options = {}) ⇒ String

Overwrites current path. By default uses relative path (started with /), if it is not overwrited in options

Parameters:

  • overwrites (Hash)

    hash of params to overwrite

  • options (Hash) (defaults to: {})

    hash of options to url_for

Returns:

  • (String)

    overwrited path



56
57
58
59
60
# File 'lib/espresso/view.rb', line 56

def overwrite_path(overwrites, options = {})
  options ||= {}
  options[:only_path] = true unless options.key?(:only_path)
  overwrite_url(overwrites, options)
end

#overwrite_url(overwrites, options = {}) ⇒ String

Overwrites current url. By default uses full path (with host), if it is not overwrited in options

Parameters:

  • overwrites (Hash)

    hash of params to overwrite

  • options (Hash) (defaults to: {})

    hash of options to url_for

Returns:

  • (String)

    overwrited url



44
45
46
47
48
49
# File 'lib/espresso/view.rb', line 44

def overwrite_url(overwrites, options = {})
  overwrites ||= {}
  options ||= {}
  options[:only_path] = false unless options.key?(:only_path)
  url_for({:overwrite_params => (overwrites || {})}.merge(options))
end

#page_title(title = nil, strip = false) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/espresso/view.rb', line 128

def page_title(title = nil, strip = false)
  @page_title = if title
                  title
                elsif @page_title
                  @page_title
                else
                  default = if !Rails.env.development?
                              default_page_title
                            else
                              nil
                            end

                  rsrc = if resource?
                           if resource.new_record?
                             resource_class.human_name
                           else
                             link_to(resource, resource_path)
                           end
                         else
                           nil
                         end

                  t("navigation.#{controller_name}.#{view_name}",
                    :default => default,
                    :resource => rsrc
                   )
                end
  if strip
    strip_tags(@page_title)
  else
    @page_title
  end
end

#paginated_list(collection_name, options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/espresso/view/will_paginate.rb', line 17

def paginated_list(collection_name, options = {})
  collection = options.delete(:collection) do
    instance_variable_get("@#{collection_name}")
  end
  prefix = options.delete(:prefix)
  prefix = prefix ? " b-list_#{prefix}_#{collection_name}" : nil
  start = (collection.respond_to?(:offset) ? collection.offset : 0) + 1
  ''.tap do |result|
    result << (:ol,
                          render(collection),
                          :class => "b-list b-list_#{collection_name}#{prefix}",
                          :start => start)
    if collection.respond_to?(:total_pages)
      result << (will_paginate(collection, options) || '')
    end
  end
end

#scope_filter(scopes) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/espresso/view/has_scope.rb', line 10

def scope_filter(scopes)
  (:div, :class => Espresso::View.scope_filter_wrapper_class) do
    (:ul, :class => Espresso::View.scope_filter_ul_class) do
      scopes.inject([]) do |list, scope|
        list << (:li, link_to_unless_current(t(".#{scope}"),
                                       collection_path(scope => true)))
        list
      end.join
    end
  end
end

#simple_searchObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/espresso/view/searchlogic.rb', line 6

def simple_search
  ''.tap do |form|
    form << form_tag(url_for(:action => :index), :method => :get)
    form << (:table, :class => 'b-search') do
      (:tr) do
        ''.tap do |result|
          result << (:td,
                                (:div,
                                            text_field_tag(:q,
                                                           params[:q],
                                                           :type => 'search'),
                                            :class => 'b-input'),
                                :class => 'input')
          result << (:td,
                                submit_tag(t('espresso.view.find',
                                             :default => 'Find!'),
                                           :class => 'submit'),
                                :class => 'button')
        end
      end
    end
    form << yield if block_given?
    form << '</form>'
  end
end

#time(time, options = {}) ⇒ String

Helper to write time in human- and machine-readable format

Parameters:

  • time (Time, DateTime)

    time to represent

Returns:

  • (String)

    <time> tag with time representation



65
66
67
68
69
70
# File 'lib/espresso/view.rb', line 65

def time(time, options = {})
  format = options.delete(:format) { :long }
  (:time,
              l(time, :format => format),
              options.merge(:time => time.xmlschema))
end

#view_nameString

Finds apropriate view name

Returns:

  • (String)

    current view name



100
101
102
103
104
105
106
# File 'lib/espresso/view.rb', line 100

def view_name
  unless @view_name
    action_name = controller.action_name
    @view_name = VIEW_PLACEHOLDERS[action_name] || action_name
  end
  @view_name
end

#will_paginate_with_i18n(collection, options = {}) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/espresso/view/will_paginate.rb', line 8

def will_paginate_with_i18n(collection, options = {})
  will_paginate_without_i18n(collection,
                             options.merge({
    :class => 'b-pagination',
    :previous_label => t('espresso.navigation.previous', :default => '← Previous'),
    :next_label =>     t('espresso.navigation.next', :default => 'Next →')}))
end