Sha256: 5471fe47ad91ff9198cdd4974cec57dc4a9ce1022754ea12d6a5870c37977343

Contents?: true

Size: 1.71 KB

Versions: 15

Compression:

Stored size: 1.71 KB

Contents

require 'hexp/h'

# Here's an example of using bare-bones Hexp together with Rails. A lot of this
# boilerplate would have to be wrapped/hidden, but it's a start.
#
# An interesting thing to note is that by overriding content_tag we can make other
# view helpers like link_to return Hexp objects rather than strings.

class UsersController < ApplicationController
  def index
    render :inline => UserIndexPage.new(User.all).to_html
  end
end

class UserIndexPage # < Hexp::Rails::Widget perhaps?
  include ActionView::Helpers::UrlHelper
  include ActionDispatch::Routing::UrlFor
  include Rails.application.routes.url_helpers

  delegate :to_html, to: :to_hexp
  attr_reader :users

  def initialize(users)
    @users = users
  end

  def to_hexp
    H[:div, [
        [:h1, "Listing users"],
        [:table, [
            [:thead, [
                [:tr, headings.map{|h| [:th, h]}]
              ]
            ],
            [:tbody, users.map do |user|
                H[:tr,
                  fields_for(user).map do |field|
                    [:td, [field]]
                  end
                ]
              end
            ]
          ]
        ]
      ]
    ]
  end

  def headings
    ['Name', 'Email', nil, nil, nil]
  end

  def fields_for(user)
    [ user.name,
      user.email,
      link_to('Show', user),
      link_to('Edit', edit_user_path(user)),
      link_to('Destroy', user, method: :delete, data: { confirm: 'Are you sure?' })
    ]
  end

  def content_tag(tag, content, attrs)
    H[tag, attrs, content]
  end

  # NullController to satisfy UrlHelper
  def controller
    Class.new do
      def respond_to?(*args)
        false
      end

      def method_missing(*args)
        return self
      end
    end.new
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
hexp-0.4.6 examples/hexp_rails.rb
hexp-0.4.5 examples/hexp_rails.rb
hexp-0.4.4 examples/hexp_rails.rb
hexp-0.4.3 examples/hexp_rails.rb
hexp-0.4.2 examples/hexp_rails.rb
hexp-0.4.1 examples/hexp_rails.rb
hexp-0.4.0.beta1 examples/hexp_rails.rb
hexp-0.3.3 examples/hexp_rails.rb
hexp-0.3.2 examples/hexp_rails.rb
hexp-0.3.1 examples/hexp_rails.rb
hexp-0.3.0 examples/hexp_rails.rb
hexp-0.2.0 examples/hexp_rails.rb
hexp-0.0.1 examples/hexp_rails.rb
hexp-0.0.1.pre4 examples/hexp_rails.rb
hexp-0.0.1.pre3 examples/hexp_rails.rb