Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created January 7, 2019 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jodosha/ff9c2e205408c27b733e93965d11a921 to your computer and use it in GitHub Desktop.
Save jodosha/ff9c2e205408c27b733e93965d11a921 to your computer and use it in GitHub Desktop.
dry-view ERB capture syntax example
# frozen_string_literal: true
require "dry/view"
module Test
class ControllerScope < Dry::View::Scope
class Form
def initialize(resource)
@resource = resource
@html = ""
end
def label(name)
@html += %(<label for="#{@resource}-#{name}">#{name.capitalize}</label>\n)
end
def text_field(name)
@html += %(<input type="text" id="#{@resource}-#{name}" name="#{@resource}[#{name}]">\n)
end
def submit(text)
@html += %(<input type="submit" value="#{text}">\n)
end
def to_s
%(<form id="new-#{@resource}" method="POST">\n#{@html}</form>\n)
end
end
def form_for(name)
Form.new(name).tap do |f|
yield f
end
end
end
end
Base = Class.new(Dry::View::Controller) do
configure do |config|
config.paths = Dir.pwd
end
end
vc = Class.new(Base) do
configure do |config|
config.scope = Test::ControllerScope
config.template = "new"
end
end.new
puts vc.call.to_s
# frozen_string_literal: true
source "https://rubygems.org"
gem "dry-view", git: "https://github.com/dry-rb/dry-view.git", branch: "erb-support"
gem "erbse"
GIT
remote: https://github.com/dry-rb/dry-view.git
revision: 861571f51638d18a362ce1923e11fce1f2ce0de0
branch: erb-support
specs:
dry-view (0.5.4)
dry-configurable (~> 0.1)
dry-core (~> 0.2)
dry-equalizer (~> 0.2)
dry-inflector (~> 0.1)
tilt (~> 2.0, >= 2.0.6)
GEM
remote: https://rubygems.org/
specs:
concurrent-ruby (1.1.4)
dry-configurable (0.7.0)
concurrent-ruby (~> 1.0)
dry-core (0.4.7)
concurrent-ruby (~> 1.0)
dry-equalizer (0.2.1)
dry-inflector (0.1.2)
erbse (0.1.3)
temple
temple (0.8.0)
tilt (2.0.9)
PLATFORMS
ruby
DEPENDENCIES
dry-view!
erbse
BUNDLED WITH
1.17.3
<h1>New Book</h1>
<div>
<%= form_for(:book) do |f| %>
<div>
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div>
<%= f.submit "Create" %>
</div>
<% end %>
</div>
@jodosha
Copy link
Author

jodosha commented Jan 7, 2019

Output

<h1>New Book!</h1>

<div>
  <form id="new-book" method="POST">
<label for="book-title">Title</label>
<input type="text" id="book-title" name="book[title]">
<input type="submit" value="Create">
</form>
</div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment