repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/slice_configurable_spec.rb
spec/unit/hanami/slice_configurable_spec.rb
# frozen_string_literal: true require "hanami/app" require "hanami/slice_configurable" RSpec.describe Hanami::SliceConfigurable, :app_integration do before do module TestApp class App < Hanami::App register_slice :main register_slice :admin end class BaseClass extend Hanami::SliceConfigurable def self.configure_for_slice(slice) traces << slice end def self.traces @traces ||= [] end def self.inherited(subclass) subclass.instance_variable_set(:@traces, traces.dup) super end end end end context "subclass inside slice namespace" do before do module Main class MySubclass < TestApp::BaseClass; end end end subject(:subclass) { Main::MySubclass } it "calls `configure_for_slice` with the slice" do expect(subclass.traces).to eq [Main::Slice] end context "further subclass, within same slice" do before do module Main class MySubSubclass < Main::MySubclass; end end end subject(:subclass) { Main::MySubSubclass } it "does not call `configure_for_slice` again" do expect(subclass.traces).to eq [Main::Slice] end end context "further subclass, within another slice namespace" do before do module Admin class MySubSubclass < Main::MySubclass; end end end subject(:subclass) { Admin::MySubSubclass } it "calls `configure_for_slice` with the other slice" do expect(subclass.traces).to eq [Main::Slice, Admin::Slice] end end end context "subclass inside slice with name overlapping another slice" do let(:app_modules) { super() << :ExternalAdmin } before do TestApp::App.register_slice :external_admin module ExternalAdmin class MySubclass < TestApp::BaseClass; end end end subject(:subclass) { ExternalAdmin::MySubclass } it "calls `configure_for_slice` with the correct matching slice" do expect(subclass.traces).to eq [ExternalAdmin::Slice] end end context "class inside app" do before do module TestApp class MySubclass < TestApp::BaseClass; end end end subject(:subclass) { TestApp::MySubclass } it "calls `configure_for_slice` with the app instance" do expect(subclass.traces).to eq [TestApp::App] end context "further subclass, within another slice namespace" do before do module Main class MySubSubclass < TestApp::MySubclass; end end end subject(:subclass) { Main::MySubSubclass } it "calls `configure_for_slice` with the other slice" do expect(subclass.traces).to eq [TestApp::App, Main::Slice] end end end context "subclass inside nested slice namespace" do before do module Main class Slice register_slice :nested end module Nested class MySubclass < TestApp::BaseClass end end end end subject(:subclass) { Main::Nested::MySubclass } it "calls `configure_for_slice` with the nested slice" do expect(subclass.traces).to eq [Main::Nested::Slice] end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/slice_spec.rb
spec/unit/hanami/slice_spec.rb
require "hanami/slice" RSpec.describe Hanami::Slice, :app_integration do before do module TestApp class App < Hanami::App end end end describe ".app" do subject(:slice) { Hanami.app.register_slice(:main) } it "returns the top-level Hanami App slice" do expect(slice.app).to eq Hanami.app end end describe ".app?" do it "returns true if the slice is Hanami.app" do subject = Hanami.app expect(subject.app?).to eq true end it "returns false if the slice is not Hanami.app" do subject = Hanami.app.register_slice(:main) expect(subject.app?).to eq false end end describe ".environment" do subject(:slice) { Hanami.app.register_slice(:main) } before do allow(slice.config).to receive(:env) { :development } end it "evaluates the block with the env matches the Hanami.env" do expect { slice.environment(:development) do config.logger.level = :info end } .to change { slice.config.logger.level } .to :info end it "yields the slice to the block" do captured_slice = nil slice.environment(:development) { |slice| captured_slice = slice } expect(captured_slice).to be slice end it "does not evaluate the block with the env does not match the Hanami.env" do expect { slice.environment(:test) do config.logger.level = :info end }.not_to(change { slice.config.logger.level }) end end describe ".prepare" do it "raises an error if the slice class is anonymous" do expect { Class.new(described_class).prepare } .to raise_error Hanami::SliceLoadError, /Slice must have a class name/ end it "does not allow special characters in slice names" do expect { Hanami.app.register_slice(:'test_$lice') } .to raise_error(ArgumentError, /must be lowercase alphanumeric text and underscores only/) end it "does not allow uppercase characters in slice names" do expect { Hanami.app.register_slice(:TEST_slice) } .to raise_error(ArgumentError, /must be lowercase alphanumeric text and underscores only/) end it "allows lowercase alphanumeric text and underscores only" do expect { Hanami.app.register_slice(:test_slice) }.not_to raise_error end it "allows single character slice names" do expect { Hanami.app.register_slice(:t) }.not_to raise_error end end describe ".source_path" do it "provides a path to the app directory for Hanami.app" do subject = Hanami.app expect(subject.source_path).to eq Hanami.app.root.join("app") end it "provides a path to the slice root for a Slice" do subject = Hanami.app.register_slice(:main) expect(subject.source_path).to eq subject.root end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/form_helper_spec.rb
spec/unit/hanami/helpers/form_helper_spec.rb
# frozen_string_literal: true require "hanami/helpers/form_helper" require "hanami/view/erb/template" RSpec.describe Hanami::Helpers::FormHelper do subject(:obj) { Class.new { include Hanami::Helpers::FormHelper attr_reader :_context def initialize(context) @_context = context end }.new(context) } let(:context) { Hanami::View::Context.new(request: request, inflector: Dry::Inflector.new) } let(:request) { Hanami::Action::Request.new(env: rack_request, params: params, session_enabled: true) } let(:rack_request) { Rack::MockRequest.env_for("http://example.com/") } let(:params) { {} } def form_for(...) obj.instance_eval { form_for(...) } end def h(&block) obj.instance_eval(&block) end def render(erb) Hanami::View::ERB::Template.new { erb }.render(obj) end describe "#form_for" do it "renders" do html = form_for("/books") expect(html).to eq %(<form action="/books" accept-charset="utf-8" method="POST"></form>) end it "allows to assign 'id' attribute" do html = form_for("/books", id: "book-form") expect(html).to eq %(<form action="/books" id="book-form" accept-charset="utf-8" method="POST"></form>) end it "allows to override 'method' attribute ('get')" do html = form_for("/books", method: "get") expect(html).to eq %(<form action="/books" method="GET" accept-charset="utf-8"></form>) end it "allows to override 'method' attribute (:get)" do html = form_for("/books", method: :get) expect(html).to eq %(<form action="/books" method="GET" accept-charset="utf-8"></form>) end it "allows to override 'method' attribute ('GET')" do html = form_for("/books", method: "GET") expect(html).to eq %(<form action="/books" method="GET" accept-charset="utf-8"></form>) end %i[patch put delete].each do |verb| it "allows to override 'method' attribute (#{verb})" do html = form_for("/books", method: verb) do |f| f.text_field "book.title" end expect(html).to eq %(<form action="/books" method="POST" accept-charset="utf-8"><input type="hidden" name="_method" value="#{verb.to_s.upcase}"><input type="text" name="book[title]" id="book-title" value=""></form>) end end it "allows to specify HTML attributes" do html = form_for("/books", class: "form-horizontal") expect(html).to eq %(<form action="/books" class="form-horizontal" accept-charset="utf-8" method="POST"></form>) end context "input name" do it "sets a base name" do expected_html = <<~HTML <form action="/books" accept-charset="utf-8" method="POST"> <input type="text" name="book[author][avatar][url]" id="book-author-avatar-url" value=""> </form> HTML html = form_for("book", "/books") do |f| f.text_field("author.avatar.url") end expect(html).to eq_html expected_html html = form_for("book", "/books") do |f| f.fields_for("author.avatar") do |fa| fa.text_field("url") end end expect(html).to eq_html expected_html end it "renders nested field names" do html = form_for("/books") do |f| f.text_field "book.author.avatar.url" end expect(html).to include %(<input type="text" name="book[author][avatar][url]" id="book-author-avatar-url" value="">) end context "using values from scope locals" do let(:values) { {book: double("book", author: double("author", avatar: double("avatar", url: val)))} } let(:val) { "https://hanami.test/avatar.png" } before do # TODO: Maybe our `obj` should actually be a real Scope subclass values = self.values obj.define_singleton_method(:_locals) { values } end it "renders with value" do html = form_for("/books") do |f| f.text_field "book.author.avatar.url" end expect(html).to include %(<input type="text" name="book[author][avatar][url]" id="book-author-avatar-url" value="#{val}">) end end context "with explicit values given" do let(:values) { {book: double("book", author: double("author", avatar: double("avatar", url: val)))} } let(:val) { "https://hanami.test/avatar.png" } it "renders with value" do html = form_for("/books", values: values) do |f| f.text_field "book.author.avatar.url" end expect(html).to include %(<input type="text" name="book[author][avatar][url]" id="book-author-avatar-url" value="#{val}">) end it "allows to override 'value' attribute" do html = form_for("/books", values: values) do |f| f.text_field "book.author.avatar.url", value: "https://hanami.test/another-avatar.jpg" end expect(html).to include %(<input type="text" name="book[author][avatar][url]" id="book-author-avatar-url" value="https://hanami.test/another-avatar.jpg">) end end context "with filled params" do let(:params) { {book: {author: {avatar: {url: val}}}} } let(:val) { "https://hanami.test/avatar.png" } it "renders with value" do html = form_for("/books") do |f| f.text_field "book.author.avatar.url" end expect(html).to include %(<input type="text" name="book[author][avatar][url]" id="book-author-avatar-url" value="#{val}">) end it "allows to override 'value' attribute" do html = form_for("/books") do |f| f.text_field "book.author.avatar.url", value: "https://hanami.test/another-avatar.jpg" end expect(html).to include %(<input type="text" name="book[author][avatar][url]" id="book-author-avatar-url" value="https://hanami.test/another-avatar.jpg">) end end end context "CSRF protection" do let(:csrf_token) { "abc123" } before do allow(request).to receive(:session) { {_csrf_token: csrf_token} } end it "injects hidden field session is enabled" do html = form_for("/books") expect(html).to eq %(<form action="/books" accept-charset="utf-8" method="POST"><input type="hidden" name="_csrf_token" value="#{csrf_token}"></form>) end context "with missing token" do let(:csrf_token) { nil } it "doesn't inject hidden field" do html = form_for("/books") expect(html).to eq %(<form action="/books" accept-charset="utf-8" method="POST"></form>) end end context "with csrf_token on get verb" do it "doesn't inject hidden field" do html = form_for("/books", method: "GET") expect(html).to eq %(<form action="/books" method="GET" accept-charset="utf-8"></form>) end end %i[patch put delete].each do |verb| it "it injects hidden field when method override (#{verb}) is active" do html = form_for("/books", method: verb) expect(html).to eq %(<form action="/books" method="POST" accept-charset="utf-8"><input type="hidden" name="_method" value="#{verb.to_s.upcase}"><input type="hidden" name="_csrf_token" value="#{csrf_token}"></form>) end end end context "CSRF meta tags" do let(:csrf_token) { "abc123" } before do allow(request).to receive(:session) { {_csrf_token: csrf_token} } end def csrf_meta_tags(...) h { csrf_meta_tags(...) } end it "prints meta tags" do html = csrf_meta_tags expect(html).to eq %(<meta name="csrf-param" content="_csrf_token"><meta name="csrf-token" content="#{csrf_token}">) end context "when CSRF token is nil" do let(:csrf_token) { nil } it "returns nil" do expect(csrf_meta_tags).to be(nil) end end end context "remote: true" do it "adds data-remote=true to form attributes" do html = form_for("/books", "data-remote": true) expect(html).to eq %(<form action="/books" data-remote="true" accept-charset="utf-8" method="POST"></form>) end it "adds data-remote=false to form attributes" do html = form_for("/books", "data-remote": false) expect(html).to eq %(<form action="/books" data-remote="false" accept-charset="utf-8" method="POST"></form>) end it "adds data-remote= to form attributes" do html = form_for("/books", "data-remote": nil) expect(html).to eq %(<form action="/books" accept-charset="utf-8" method="POST"></form>) end end context "explicitly given params" do let(:params) { {song: {title: "Orphans"}} } let(:given_params) { {song: {title: "Arabesque"}} } let(:action) { "/songs" } it "renders" do html = form_for("/songs", params: given_params) do |f| f.text_field "song.title" end expect(html).to eq(%(<form action="/songs" accept-charset="utf-8" method="POST"><input type="text" name="song[title]" id="song-title" value="Arabesque"></form>)) end end end describe "#fields_for" do it "renders" do html = render(<<~ERB) <%= form_for("/books") do |f| %> <% f.fields_for "book.categories" do |fa| %> <%= fa.text_field :name %> <% fa.fields_for :subcategories do |fb| %> <%= fb.text_field :name %> <% end %> <%= fa.text_field :name2 %> <% end %> <%= f.text_field "book.title" %> <% end %> ERB expect(html).to eq_html <<~HTML <form action="/books" accept-charset="utf-8" method="POST"> <input type="text" name="book[categories][name]" id="book-categories-name" value=""> <input type="text" name="book[categories][subcategories][name]" id="book-categories-subcategories-name" value=""> <input type="text" name="book[categories][name2]" id="book-categories-name2" value=""> <input type="text" name="book[title]" id="book-title" value=""> </form> HTML end describe "with filled params" do let(:params) { {book: {title: "TDD", categories: {name: "foo", name2: "bar", subcategories: {name: "sub"}}}} } it "renders" do html = render(<<~ERB) <%= form_for("/books") do |f| %> <% f.fields_for "book.categories" do |fa| %> <%= fa.text_field :name %> <% fa.fields_for :subcategories do |fb| %> <%= fb.text_field :name %> <% end %> <%= fa.text_field :name2 %> <% end %> <%= f.text_field "book.title" %> <% end %> ERB expect(html).to eq_html <<~HTML <form action="/books" accept-charset="utf-8" method="POST"> <input type="text" name="book[categories][name]" id="book-categories-name" value="foo"> <input type="text" name="book[categories][subcategories][name]" id="book-categories-subcategories-name" value="sub"> <input type="text" name="book[categories][name2]" id="book-categories-name2" value="bar"> <input type="text" name="book[title]" id="book-title" value="TDD"> </form> HTML end end end describe "#fields_for_collection" do let(:params) { {book: {categories: [{name: "foo", new: true, genre: nil}]}} } it "renders" do html = render(<<~ERB) <%= form_for("/books") do |f| %> <% f.fields_for_collection "book.categories" do |fa| %> <%= fa.text_field :name %> <%= fa.hidden_field :name %> <%= fa.text_area :name %> <%= fa.check_box :new %> <%= fa.select :genre, [%w[Terror terror], %w[Comedy comedy]] %> <%= fa.color_field :name %> <%= fa.date_field :name %> <%= fa.datetime_field :name %> <%= fa.datetime_local_field :name %> <%= fa.time_field :name %> <%= fa.month_field :name %> <%= fa.week_field :name %> <%= fa.email_field :name %> <%= fa.url_field :name %> <%= fa.tel_field :name %> <%= fa.file_field :name %> <%= fa.number_field :name %> <%= fa.range_field :name %> <%= fa.search_field :name %> <%= fa.radio_button :name, "Fiction" %> <%= fa.password_field :name %> <%= fa.datalist :name, ["Italy", "United States"], "books" %> <% end %> <% end %> ERB expected = <<~HTML <form action="/books" enctype="multipart/form-data" accept-charset="utf-8" method="POST"> <input type="text" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="hidden" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <textarea name="book[categories][][name]" id="book-categories-0-name"> foo</textarea> <input type="hidden" name="book[categories][][new]" value="0"><input type="checkbox" name="book[categories][][new]" id="book-categories-0-new" value="1" checked="checked"> <select name="book[categories][][genre]" id="book-categories-0-genre"><option value="terror">Terror</option><option value="comedy">Comedy</option></select> <input type="color" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="date" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="datetime" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="datetime-local" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="time" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="month" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="week" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="email" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="url" name="book[categories][][name]" id="book-categories-0-name" value=""> <input type="tel" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="file" name="book[categories][][name]" id="book-categories-0-name"> <input type="number" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="range" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="search" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="radio" name="book[categories][][name]" value="Fiction"> <input type="password" name="book[categories][][name]" id="book-categories-0-name" value=""> <input type="text" name="book[categories][][name]" id="book-categories-0-name" value="foo" list="books"><datalist id="books"><option value="Italy"></option><option value="United States"></option></datalist> </form> HTML expect(html).to eq_html(expected) end context "with base name" do let(:params) { {book: {categories: [{name: "foo"}, {name: "bar"}]}} } it "renders" do html = render(<<~ERB) <%= form_for("book", "/books") do |f| %> <% f.fields_for_collection "categories" do |fa| %> <%= fa.text_field :name %> <% end %> <% end %> ERB expected = <<~HTML <form action="/books" accept-charset="utf-8" method="POST"> <input type="text" name="book[categories][][name]" id="book-categories-0-name" value="foo"> <input type="text" name="book[categories][][name]" id="book-categories-1-name" value="bar"> </form> HTML expect(html).to eq_html(expected) end end end describe "#label" do it "renders capitalized string" do html = form_for("/books") do |f| f.label "book.free_shipping" end expect(html).to include %(<label for="book-free-shipping">Free shipping</label>) end it "accepts a symbol" do html = form_for("/books") do |f| f.label :free_shipping end expect(html).to include %(<label for="free-shipping">Free shipping</label>) end it "accepts a string as custom content" do html = form_for("/books") do |f| f.label "Free Shipping!", for: "book.free_shipping" end expect(html).to include %(<label for="book-free-shipping">Free Shipping!</label>) end it "renders a label with block" do html = render(<<~ERB) <%= form_for "/books" do |f| %> <%= f.label for: "book.free_shipping" do %> Free Shipping <%= tag.abbr "*", title: "optional", aria: {label: "optional"} %> <% end %> <% end %> ERB expect(html).to eq <<~HTML <form action="/books" accept-charset="utf-8" method="POST"> <label for="book-free-shipping"> Free Shipping <abbr title="optional" aria-label="optional">*</abbr> </label> </form> HTML end end describe "#button" do it "renders a button" do html = form_for("/books") do |f| f.button "Click me" end expect(html).to include %(<button>Click me</button>) end it "renders a button with HTML attributes" do html = form_for("/books") do |f| f.button "Click me", class: "btn btn-secondary" end expect(html).to include(%(<button class="btn btn-secondary">Click me</button>)) end it "renders a button with block" do html = render(<<~ERB) <%= form_for("/books") do |f| %> <%= f.button class: "btn btn-secondary" do %> <%= tag.span class: "oi oi-check" %> <% end %> <% end %> ERB expect(html).to eq <<~HTML <form action="/books" accept-charset="utf-8" method="POST"> <button class="btn btn-secondary"> <span class="oi oi-check"></span> </button> </form> HTML end end describe "#submit" do it "renders a submit button" do html = form_for("/books") do |f| f.submit "Create" end expect(html).to include %(<button type="submit">Create</button>) end it "renders a submit button with HTML attributes" do html = form_for("/books") do |f| f.submit "Create", class: "btn btn-primary" end expect(html).to include %(<button type="submit" class="btn btn-primary">Create</button>) end it "renders a submit button with block" do html = render(<<~ERB) <%= form_for "/books" do |f| %> <%= f.submit class: "btn btn-primary" do %> <%= tag.span class: "oi oi-check" %> <% end %> <% end %> ERB expect(html).to eq <<~HTML <form action="/books" accept-charset="utf-8" method="POST"> <button type="submit" class="btn btn-primary"> <span class="oi oi-check"></span> </button> </form> HTML end end describe "#image_button" do it "renders an image button" do html = form_for("/books") do |f| f.image_button "https://hanamirb.org/assets/image_button.png" end expect(html).to include %(<input type="image" src="https://hanamirb.org/assets/image_button.png">) end it "renders an image button with HTML attributes" do html = form_for("/books") do |f| f.image_button "https://hanamirb.org/assets/image_button.png", name: "image", width: "50" end expect(html).to include %(<input name="image" width="50" type="image" src="https://hanamirb.org/assets/image_button.png">) end it "prevents XSS attacks" do html = form_for("/books") do |f| f.image_button "<script>alert('xss');</script>" end expect(html).to include %(<input type="image" src="">) end end # # FIELDSET # describe "#fieldset" do it "renders a fieldset" do html = render(<<~ERB) <%= form_for "/books" do |f| %> <%= f.fieldset do %> <%= tag.legend "Author" %> <%= f.label "author.name" %> <%= f.text_field "author.name" %> <% end %> <% end %> ERB expect(html).to include_html <<~HTML <fieldset> <legend>Author</legend> <label for="author-name">Name</label> <input type="text" name="author[name]" id="author-name" value=""> </fieldset> HTML end end # # INPUT FIELDS # describe "#check_box" do it "renders" do html = form_for("/books") do |f| f.check_box "book.free_shipping" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="0"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="1">) end it "allows to pass checked and unchecked value" do html = form_for("/books") do |f| f.check_box "book.free_shipping", checked_value: "true", unchecked_value: "false" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="false"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="true">) end it "allows to override 'id' attribute" do html = form_for("/books") do |f| f.check_box "book.free_shipping", id: "shipping" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="0"><input type="checkbox" name="book[free_shipping]" id="shipping" value="1">) end it "allows to override 'name' attribute" do html = form_for("/books") do |f| f.check_box "book.free_shipping", name: "book[free]" end expect(html).to include %(<input type="hidden" name="book[free]" value="0"><input type="checkbox" name="book[free]" id="book-free-shipping" value="1">) end it "allows to specify HTML attributes" do html = form_for("/books") do |f| f.check_box "book.free_shipping", class: "form-control" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="0"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="1" class="form-control">) end it "doesn't render hidden field if 'value' attribute is specified" do html = form_for("/books") do |f| f.check_box "book.free_shipping", value: "ok" end expect(html).not_to include %(<input type="hidden" name="book[free_shipping]" value="0">) expect(html).to include %(<input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="ok">) end it "renders hidden field if 'value' attribute and 'unchecked_value' option are both specified" do html = form_for("/books") do |f| f.check_box "book.free_shipping", value: "yes", unchecked_value: "no" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="no"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="yes">) end it "handles multiple checkboxes" do html = render(<<~ERB) <%= form_for("/books") do |f| %> <%= f.check_box "book.languages", name: "book[languages][]", value: "italian", id: nil %> <%= f.check_box "book.languages", name: "book[languages][]", value: "english", id: nil %> <% end %> ERB expect(html).to include_html <<~HTML <input type="checkbox" name="book[languages][]" value="italian"> <input type="checkbox" name="book[languages][]" value="english"> HTML end context "with filled params" do let(:params) { {book: {free_shipping: val}} } context "when the params value equals to check box value" do let(:val) { "1" } it "renders with 'checked' attribute" do html = form_for("/books") do |f| f.check_box "book.free_shipping" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="0"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="1" checked="checked">) end end context "when the params value equals to the hidden field value" do let(:val) { "0" } it "renders without 'checked' attribute" do html = form_for("/books") do |f| f.check_box "book.free_shipping" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="0"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="1">) end it "allows to override 'checked' attribute" do html = form_for("/books") do |f| f.check_box "book.free_shipping", checked: "checked" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="0"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="1" checked="checked">) end end context "with a boolean argument" do let(:val) { true } it "renders with 'checked' attribute" do html = form_for("/books") do |f| f.check_box "book.free_shipping" end expect(html).to include %(<input type="hidden" name="book[free_shipping]" value="0"><input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="1" checked="checked">) end end context "when multiple params are present" do let(:params) { {book: {languages: ["italian"]}} } it "handles multiple checkboxes" do html = render(<<~ERB) <%= form_for("/books") do |f| %> <%= f.check_box "book.languages", name: "book[languages][]", value: "italian", id: nil %> <%= f.check_box "book.languages", name: "book[languages][]", value: "english", id: nil %> <% end %> ERB expect(html).to include_html <<~HTML <input type="checkbox" name="book[languages][]" value="italian" checked="checked"> <input type="checkbox" name="book[languages][]" value="english"> HTML end end context "checked_value is boolean" do let(:params) { {book: {free_shipping: "true"}} } it "renders with 'checked' attribute" do html = form_for("/books") do |f| f.check_box "book.free_shipping", checked_value: true end expect(html).to include %(<input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="true" checked="checked">) end end end context "automatic values" do context "checkbox" do context "value boolean, helper boolean, values differ" do let(:values) { {book: Struct.new(:free_shipping).new(false)} } it "renders" do html = form_for("/books", values: values) do |f| f.check_box "book.free_shipping", checked_value: true end expect(html).to include %(<input type="checkbox" name="book[free_shipping]" id="book-free-shipping" value="true">) end end end end end describe "#color_field" do it "renders" do html = form_for("/books") do |f| f.color_field "book.cover" end expect(html).to include %(<input type="color" name="book[cover]" id="book-cover" value="">) end it "allows to override 'id' attribute" do html = form_for("/books") do |f| f.color_field "book.cover", id: "b-cover" end expect(html).to include %(<input type="color" name="book[cover]" id="b-cover" value="">) end it "allows to override 'name' attribute" do html = form_for("/books") do |f| f.color_field "book.cover", name: "cover" end expect(html).to include %(<input type="color" name="cover" id="book-cover" value="">) end it "allows to override 'value' attribute" do html = form_for("/books") do |f| f.color_field "book.cover", value: "#ffffff" end expect(html).to include %(<input type="color" name="book[cover]" id="book-cover" value="#ffffff">) end it "allows to specify HTML attributes" do html = form_for("/books") do |f| f.color_field "book.cover", class: "form-control" end expect(html).to include %(<input type="color" name="book[cover]" id="book-cover" value="" class="form-control">) end context "with values" do let(:values) { {book: Struct.new(:cover).new(val)} } let(:val) { "#d3397e" } it "renders with value" do html = form_for("/books", values: values) do |f| f.color_field "book.cover" end expect(html).to include %(<input type="color" name="book[cover]" id="book-cover" value="#{val}">) end it "allows to override 'value' attribute" do html = form_for("/books", values: values) do |f| f.color_field "book.cover", value: "#000000" end expect(html).to include %(<input type="color" name="book[cover]" id="book-cover" value="#000000">) end end context "with filled params" do let(:params) { {book: {cover: val}} } let(:val) { "#d3397e" } it "renders with value" do html = form_for("/books") do |f| f.color_field "book.cover" end expect(html).to include %(<input type="color" name="book[cover]" id="book-cover" value="#{val}">) end it "allows to override 'value' attribute" do html = form_for("/books") do |f| f.color_field "book.cover", value: "#000000" end expect(html).to include %(<input type="color" name="book[cover]" id="book-cover" value="#000000">) end end end describe "#date_field" do it "renders" do html = form_for("/books") do |f| f.date_field "book.release_date" end expect(html).to include %(<input type="date" name="book[release_date]" id="book-release-date" value="">) end it "allows to override 'id' attribute" do html = form_for("/books") do |f| f.date_field "book.release_date", id: "release-date" end expect(html).to include %(<input type="date" name="book[release_date]" id="release-date" value="">) end it "allows to override 'name' attribute" do html = form_for("/books") do |f| f.date_field "book.release_date", name: "release_date" end expect(html).to include %(<input type="date" name="release_date" id="book-release-date" value="">) end it "allows to override 'value' attribute" do html = form_for("/books") do |f| f.date_field "book.release_date", value: "2015-02-19" end expect(html).to include %(<input type="date" name="book[release_date]" id="book-release-date" value="2015-02-19">) end it "allows to specify HTML attributes" do html = form_for("/books") do |f| f.date_field "book.release_date", class: "form-control" end expect(html).to include %(<input type="date" name="book[release_date]" id="book-release-date" value="" class="form-control">) end context "with values" do let(:values) { {book: Struct.new(:release_date).new(val)} } let(:val) { "2014-06-23" } it "renders with value" do html = form_for("/books", values: values) do |f| f.date_field "book.release_date" end expect(html).to include %(<input type="date" name="book[release_date]" id="book-release-date" value="#{val}">) end it "allows to override 'value' attribute" do html = form_for("/books", values: values) do |f| f.date_field "book.release_date", value: "2015-03-23" end expect(html).to include %(<input type="date" name="book[release_date]" id="book-release-date" value="2015-03-23">) end end context "with filled params" do let(:params) { {book: {release_date: val}} } let(:val) { "2014-06-23" } it "renders with value" do html = form_for("/books") do |f| f.date_field "book.release_date" end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
true
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/assets_helper/stylesheet_tag_spec.rb
spec/unit/hanami/helpers/assets_helper/stylesheet_tag_spec.rb
# frozen_string_literal: true RSpec.describe Hanami::Helpers::AssetsHelper, "#stylesheet", :app_integration do subject(:obj) { helpers = described_class Class.new { include helpers attr_reader :_context def initialize(context) @_context = context end }.new(context) } def stylesheet_tag(...) subject.stylesheet_tag(...) end let(:context) { TestApp::Views::Context.new } let(:root) { make_tmp_directory } before do with_directory(root) do write "config/app.rb", <<~RUBY module TestApp class App < Hanami::App config.logger.stream = StringIO.new end end RUBY write "app/views/context.rb", <<~RUBY # auto_register: false require "hanami/view/context" module TestApp module Views class Context < Hanami::View::Context end end end RUBY write "app/assets/js/app.ts", <<~JS import "../css/app.css"; console.log("Hello from index.ts"); JS write "app/assets/css/app.css", <<~CSS .btn { background: #f00; } CSS stub_assets("main.css") require "hanami/setup" before_prepare if respond_to?(:before_prepare) require "hanami/prepare" end end it "returns an instance of SafeString" do actual = stylesheet_tag("main") expect(actual).to be_instance_of(::Hanami::View::HTML::SafeString) end it "is aliased as #stylesheet_tag" do expect(subject.stylesheet_tag("main")).to eq stylesheet_tag("main") end it "renders <link> tag" do actual = stylesheet_tag("main") expect(actual).to eq(%(<link href="/assets/main.css" type="text/css" rel="stylesheet">)) end xit "renders <link> tag without appending ext after query string" do actual = stylesheet_tag("fonts?font=Helvetica") expect(actual).to eq(%(<link href="/assets/fonts?font=Helvetica" type="text/css" rel="stylesheet">)) end it "renders <link> tag with an integrity attribute" do actual = stylesheet_tag("main", integrity: "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC") expect(actual).to eq(%(<link href="/assets/main.css" type="text/css" rel="stylesheet" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" crossorigin="anonymous">)) end it "renders <link> tag with a crossorigin attribute" do actual = stylesheet_tag("main", integrity: "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC", crossorigin: "use-credentials") expect(actual).to eq(%(<link href="/assets/main.css" type="text/css" rel="stylesheet" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" crossorigin="use-credentials">)) end it "ignores href passed as an option" do actual = stylesheet_tag("main", href: "wrong") expect(actual).to eq(%(<link href="/assets/main.css" type="text/css" rel="stylesheet">)) end describe "subresource_integrity mode" do def before_prepare Hanami.app.config.assets.subresource_integrity = [:sha384] end before { compile_assets! } it "includes subresource_integrity and crossorigin attributes" do actual = stylesheet_tag("app") expect(actual).to match(%r{<link href="/assets/app-[A-Z0-9]{8}.css" type="text/css" rel="stylesheet" integrity="sha384-[A-Za-z0-9+/]{64}" crossorigin="anonymous">}) end end describe "cdn mode" do let(:base_url) { "https://hanami.test" } def before_prepare Hanami.app.config.assets.base_url = base_url end it "returns absolute url for href attribute" do actual = stylesheet_tag("main") expect(actual).to eq(%(<link href="#{base_url}/assets/main.css" type="text/css" rel="stylesheet">)) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/assets_helper/asset_url_spec.rb
spec/unit/hanami/helpers/assets_helper/asset_url_spec.rb
# frozen_string_literal: true RSpec.describe Hanami::Helpers::AssetsHelper, "#asset_url", :app_integration do subject(:obj) { helpers = described_class Class.new { include helpers attr_reader :_context def initialize(context) @_context = context end }.new(context) } def asset_url(...) subject.asset_url(...) end let(:context) { TestApp::Views::Context.new } let(:root) { make_tmp_directory } before do with_directory(root) do write "config/app.rb", <<~RUBY module TestApp class App < Hanami::App config.logger.stream = StringIO.new end end RUBY write "app/views/context.rb", <<~RUBY # auto_register: false require "hanami/view/context" module TestApp module Views class Context < Hanami::View::Context end end end RUBY write "app/assets/js/app.ts", <<~JS import "../css/app.css"; console.log("Hello from index.ts"); JS write "app/assets/css/app.css", <<~CSS .btn { background: #f00; } CSS stub_assets("app.js") require "hanami/setup" before_prepare if respond_to?(:before_prepare) require "hanami/prepare" end end context "when configurated relative path only" do context "without manifest" do it "returns the relative URL to the asset" do expect(asset_url("app.js")).to eq("/assets/app.js") end it "returns absolute URL if the argument is an absolute URL" do result = asset_url("http://assets.hanamirb.org/assets/application.css") expect(result).to eq("http://assets.hanamirb.org/assets/application.css") end end context "with manifest" do before { compile_assets! } it "returns the relative URL to the asset" do expect(asset_url("app.js")).to match(%r{/assets/app-[A-Z0-9]{8}\.js}) end end end context "when configured with base url" do let(:base_url) { "https://hanami.test" } def before_prepare Hanami.app.config.assets.base_url = base_url end context "without manifest" do it "returns the absolute URL to the asset" do expect(asset_url("app.js")).to eq("#{base_url}/assets/app.js") end end context "with manifest" do before { compile_assets! } it "returns the relative path to the asset" do expect(asset_url("app.js")).to match(%r{#{base_url}/assets/app-[A-Z0-9]{8}.js}) end end end context "given an asset object" do it "returns the URL for the asset" do asset = Hanami::Assets::Asset.new( path: "/foo/bar.js", base_url: Hanami.app.config.assets.base_url ) expect(asset_url(asset)).to eq "/foo/bar.js" end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/assets_helper/image_tag_spec.rb
spec/unit/hanami/helpers/assets_helper/image_tag_spec.rb
# frozen_string_literal: true RSpec.describe Hanami::Helpers::AssetsHelper, "#image", :app_integration do subject(:obj) { helpers = described_class Class.new { include helpers attr_reader :_context def initialize(context) @_context = context end }.new(context) } def image_tag(...) subject.image_tag(...) end let(:root) { make_tmp_directory } let(:context) { TestApp::Views::Context.new } before do with_directory(root) do write "config/app.rb", <<~RUBY module TestApp class App < Hanami::App config.logger.stream = StringIO.new end end RUBY write "app/views/context.rb", <<~RUBY # auto_register: false require "hanami/view/context" module TestApp module Views class Context < Hanami::View::Context end end end RUBY stub_assets("application.jpg") require "hanami/setup" before_prepare if respond_to?(:before_prepare) require "hanami/prepare" end end it "returns an instance of HtmlBuilder" do actual = image_tag("application.jpg") expect(actual).to be_instance_of(::Hanami::View::HTML::SafeString) end it "renders an <img> tag" do actual = image_tag("application.jpg").to_s expect(actual).to eq(%(<img src="/assets/application.jpg" alt="Application">)) end it "custom alt" do actual = image_tag("application.jpg", alt: "My Alt").to_s expect(actual).to eq(%(<img src="/assets/application.jpg" alt="My Alt">)) end it "custom data attribute" do actual = image_tag("application.jpg", "data-user-id" => 5).to_s expect(actual).to eq(%(<img src="/assets/application.jpg" alt="Application" data-user-id="5">)) end it "ignores src passed as an option" do actual = image_tag("application.jpg", src: "wrong").to_s expect(actual).to eq(%(<img src="/assets/application.jpg" alt="Application">)) end describe "cdn mode" do let(:base_url) { "https://hanami.test" } def before_prepare Hanami.app.config.assets.base_url = "https://hanami.test" end it "returns absolute url for src attribute" do actual = image_tag("application.jpg").to_s expect(actual).to eq(%(<img src="#{base_url}/assets/application.jpg" alt="Application">)) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/assets_helper/favicon_tag_spec.rb
spec/unit/hanami/helpers/assets_helper/favicon_tag_spec.rb
# frozen_string_literal: true RSpec.describe Hanami::Helpers::AssetsHelper, "#favicon", :app_integration do subject(:obj) { helpers = described_class Class.new { include helpers attr_reader :_context def initialize(context) @_context = context end }.new(context) } def favicon_tag(...) obj.instance_eval { favicon_tag(...) } end let(:root) { make_tmp_directory } let(:context) { TestApp::Views::Context.new } before do with_directory(root) do write "config/app.rb", <<~RUBY module TestApp class App < Hanami::App config.logger.stream = StringIO.new end end RUBY write "app/views/context.rb", <<~RUBY # auto_register: false require "hanami/view/context" module TestApp module Views class Context < Hanami::View::Context end end end RUBY stub_assets("favicon.ico", "favicon.png") require "hanami/setup" before_prepare if respond_to?(:before_prepare) require "hanami/prepare" end end it "returns an instance of SafeString" do actual = favicon_tag expect(actual).to be_instance_of(::Hanami::View::HTML::SafeString) end it "renders <link> tag" do actual = favicon_tag.to_s expect(actual).to eq(%(<link href="/assets/favicon.ico" rel="shortcut icon" type="image/x-icon">)) end it "renders with HTML attributes" do actual = favicon_tag("favicon.png", rel: "icon", type: "image/png").to_s expect(actual).to eq(%(<link href="/assets/favicon.png" rel="icon" type="image/png">)) end it "ignores href passed as an option" do actual = favicon_tag("favicon.png", href: "wrong").to_s expect(actual).to eq(%(<link href="/assets/favicon.png" rel="shortcut icon" type="image/x-icon">)) end describe "cdn mode" do let(:base_url) { "https://hanami.test" } def before_prepare Hanami.app.config.assets.base_url = "https://hanami.test" end it "returns absolute url for href attribute" do actual = favicon_tag.to_s expect(actual).to eq(%(<link href="#{base_url}/assets/favicon.ico" rel="shortcut icon" type="image/x-icon">)) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/assets_helper/audio_tag_spec.rb
spec/unit/hanami/helpers/assets_helper/audio_tag_spec.rb
# frozen_string_literal: true RSpec.describe Hanami::Helpers::AssetsHelper, "#audio", :app_integration do subject(:obj) { helpers = described_class Class.new { include helpers attr_reader :_context def initialize(context) @_context = context end }.new(context) } def audio_tag(...) subject.audio_tag(...) end let(:context) { TestApp::Views::Context.new } let(:root) { make_tmp_directory } before do with_directory(root) do write "config/app.rb", <<~RUBY module TestApp class App < Hanami::App config.logger.stream = StringIO.new end end RUBY write "app/views/context.rb", <<~RUBY # auto_register: false require "hanami/view/context" module TestApp module Views class Context < Hanami::View::Context end end end RUBY stub_assets("song.ogg", "song.pt-BR.vtt") require "hanami/setup" before_prepare if respond_to?(:before_prepare) require "hanami/prepare" end end it "returns an instance of HtmlBuilder" do actual = audio_tag("song.ogg") expect(actual).to be_instance_of(::Hanami::View::HTML::SafeString) end it "renders <audio> tag" do actual = audio_tag("song.ogg").to_s expect(actual).to eq(%(<audio src="/assets/song.ogg"></audio>)) end it "renders with html attributes" do actual = audio_tag("song.ogg", autoplay: true, controls: true).to_s expect(actual).to eq(%(<audio autoplay="autoplay" controls="controls" src="/assets/song.ogg"></audio>)) end it "renders with fallback content" do actual = audio_tag("song.ogg") do "Your browser does not support the audio tag" end.to_s expect(actual).to eq(%(<audio src="/assets/song.ogg">Your browser does not support the audio tag</audio>)) end it "renders with tracks" do actual = audio_tag("song.ogg") do tag.track kind: "captions", src: subject.asset_url("song.pt-BR.vtt"), srclang: "pt-BR", label: "Portuguese" end.to_s expect(actual).to eq(%(<audio src="/assets/song.ogg"><track kind="captions" src="/assets/song.pt-BR.vtt" srclang="pt-BR" label="Portuguese"></audio>)) end xit "renders with sources" do actual = audio do tag.text "Your browser does not support the audio tag" tag.source src: subject.asset_url("song.ogg"), type: "audio/ogg" tag.source src: subject.asset_url("song.wav"), type: "audio/wav" end.to_s expect(actual).to eq(%(<audio>Your browser does not support the audio tag<source src="/assets/song.ogg" type="audio/ogg"><source src="/assets/song.wav" type="audio/wav"></audio>)) end it "raises an exception when no arguments" do expect do audio_tag end.to raise_error( ArgumentError, "You should provide a source via `src` option or with a `source` HTML tag" ) end it "raises an exception when no src and no block" do expect do audio_tag(controls: true) end.to raise_error( ArgumentError, "You should provide a source via `src` option or with a `source` HTML tag" ) end describe "cdn mode" do let(:base_url) { "https://hanami.test" } def before_prepare Hanami.app.config.assets.base_url = base_url end it "returns absolute url for src attribute" do actual = audio_tag("song.ogg").to_s expect(actual).to eq(%(<audio src="#{base_url}/assets/song.ogg"></audio>)) end end private def tag(...) subject.__send__(:tag, ...) end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/assets_helper/video_tag_spec.rb
spec/unit/hanami/helpers/assets_helper/video_tag_spec.rb
# frozen_string_literal: true RSpec.describe Hanami::Helpers::AssetsHelper, "#video", :app_integration do subject(:obj) { helpers = described_class Class.new { include helpers attr_reader :_context def initialize(context) @_context = context end }.new(context) } def video_tag(...) subject.video_tag(...) end let(:context) { TestApp::Views::Context.new } let(:root) { make_tmp_directory } before do with_directory(root) do write "config/app.rb", <<~RUBY module TestApp class App < Hanami::App config.logger.stream = StringIO.new end end RUBY write "app/views/context.rb", <<~RUBY # auto_register: false require "hanami/view/context" module TestApp module Views class Context < Hanami::View::Context end end end RUBY stub_assets("movie.mp4", "movie.en.vtt") require "hanami/setup" before_prepare if respond_to?(:before_prepare) require "hanami/prepare" end end it "returns an instance of HtmlBuilder" do actual = video_tag("movie.mp4") expect(actual).to be_instance_of(::Hanami::View::HTML::SafeString) end it "renders <video> tag" do actual = video_tag("movie.mp4").to_s expect(actual).to eq(%(<video src="/assets/movie.mp4"></video>)) end it "is aliased as #video_tag" do expect(video_tag("movie.mp4")).to eq(subject.video_tag("movie.mp4")) end it "renders with html attributes" do actual = video_tag("movie.mp4", autoplay: true, controls: true).to_s expect(actual).to eq(%(<video autoplay="autoplay" controls="controls" src="/assets/movie.mp4"></video>)) end it "renders with fallback content" do actual = video_tag("movie.mp4") do "Your browser does not support the video tag" end.to_s expect(actual).to eq(%(<video src="/assets/movie.mp4">Your browser does not support the video tag</video>)) end it "renders with tracks" do actual = video_tag("movie.mp4") do tag.track kind: "captions", src: subject.asset_url("movie.en.vtt"), srclang: "en", label: "English" end.to_s expect(actual).to eq(%(<video src="/assets/movie.mp4"><track kind="captions" src="/assets/movie.en.vtt" srclang="en" label="English"></video>)) end xit "renders with sources" do actual = subject.video do tag.text "Your browser does not support the video tag" tag.source src: subject.asset_url("movie.mp4"), type: "video/mp4" tag.source src: subject.asset_url("movie.ogg"), type: "video/ogg" end.to_s expect(actual).to eq(%(<video>Your browser does not support the video tag<source src="/assets/movie.mp4" type="video/mp4"><source src="/assets/movie.ogg" type="video/ogg"></video>)) end it "raises an exception when no arguments" do expect do video_tag end.to raise_error( ArgumentError, "You should provide a source via `src` option or with a `source` HTML tag" ) end it "raises an exception when no src and no block" do expect do video_tag(content: true) end.to raise_error( ArgumentError, "You should provide a source via `src` option or with a `source` HTML tag" ) end describe "cdn mode" do let(:base_url) { "https://hanami.test" } def before_prepare Hanami.app.config.assets.base_url = "https://hanami.test" end it "returns absolute url for src attribute" do actual = video_tag("movie.mp4").to_s expect(actual).to eq(%(<video src="#{base_url}/assets/movie.mp4"></video>)) end end private def tag(...) subject.__send__(:tag, ...) end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/helpers/assets_helper/javascript_tag_spec.rb
spec/unit/hanami/helpers/assets_helper/javascript_tag_spec.rb
# frozen_string_literal: true RSpec.describe Hanami::Helpers::AssetsHelper, "#javascript", :app_integration do subject(:obj) { helpers = described_class Class.new { include helpers attr_reader :_context def initialize(context) @_context = context end }.new(context) } def javascript_tag(...) subject.javascript_tag(...) end let(:context) { TestApp::Views::Context.new } let(:root) { make_tmp_directory } before do with_directory(root) do write "config/app.rb", <<~RUBY module TestApp class App < Hanami::App config.logger.stream = StringIO.new end end RUBY write "app/views/context.rb", <<~RUBY # auto_register: false require "hanami/view/context" module TestApp module Views class Context < Hanami::View::Context end end end RUBY write "app/assets/js/app.ts", <<~JS import "../css/app.css"; console.log("Hello from index.ts"); JS write "app/assets/css/app.css", <<~CSS .btn { background: #f00; } CSS stub_assets("feature-a.js") require "hanami/setup" before_prepare if respond_to?(:before_prepare) require "hanami/prepare" end end it "returns an instance of SafeString" do actual = javascript_tag("feature-a") expect(actual).to be_instance_of(::Hanami::View::HTML::SafeString) end it "is aliased as #javascript_tag" do expect(subject.javascript_tag("feature-a")).to eq javascript_tag("feature-a") end it "renders <script> tag" do actual = javascript_tag("feature-a") expect(actual).to eq(%(<script src="/assets/feature-a.js" type="text/javascript"></script>)) end xit "renders <script> tag without appending ext after query string" do actual = javascript_tag("feature-x?callback=init") expect(actual).to eq(%(<script src="/assets/feature-x?callback=init" type="text/javascript"></script>)) end it "renders <script> tag with a defer attribute" do actual = javascript_tag("feature-a", defer: true) expect(actual).to eq(%(<script src="/assets/feature-a.js" type="text/javascript" defer="defer"></script>)) end it "renders <script> tag with an integrity attribute" do actual = javascript_tag("feature-a", integrity: "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC") expect(actual).to eq(%(<script src="/assets/feature-a.js" type="text/javascript" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" crossorigin="anonymous"></script>)) end it "renders <script> tag with a crossorigin attribute" do actual = javascript_tag("feature-a", integrity: "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC", crossorigin: "use-credentials") expect(actual).to eq(%(<script src="/assets/feature-a.js" type="text/javascript" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" crossorigin="use-credentials"></script>)) end it "ignores src passed as an option" do actual = javascript_tag("feature-a", src: "wrong") expect(actual).to eq(%(<script src="/assets/feature-a.js" type="text/javascript"></script>)) end describe "async option" do it "renders <script> tag with an async=true if async option is true" do actual = javascript_tag("feature-a", async: true) expect(actual).to eq(%(<script src="/assets/feature-a.js" type="text/javascript" async="async"></script>)) end it "renders <script> tag without an async=true if async option is false" do actual = javascript_tag("feature-a", async: false) expect(actual).to eq(%(<script src="/assets/feature-a.js" type="text/javascript"></script>)) end end describe "subresource_integrity mode" do def before_prepare Hanami.app.config.assets.subresource_integrity = [:sha384] end before { compile_assets! } it "includes subresource_integrity and crossorigin attributes" do actual = javascript_tag("app") expect(actual).to match(%r{<script src="/assets/app-[A-Z0-9]{8}.js" type="text/javascript" integrity="sha384-[A-Za-z0-9+/]{64}" crossorigin="anonymous"></script>}) end end describe "cdn mode" do let(:base_url) { "https://hanami.test" } def before_prepare Hanami.app.config.assets.base_url = "https://hanami.test" end it "returns absolute url for src attribute" do actual = javascript_tag("feature-a") expect(actual).to eq(%(<script src="#{base_url}/assets/feature-a.js" type="text/javascript"></script>)) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/settings/env_store_spec.rb
spec/unit/hanami/settings/env_store_spec.rb
# frozen_string_literal: true require "hanami/settings/env_store" RSpec.describe Hanami::Settings::EnvStore do it "defaults to using ENV as the store" do orig_env = ENV.to_h ENV["FOO"] = "bar" expect(described_class.new.fetch("FOO")).to eq "bar" ENV.replace(orig_env) end describe "#fetch" do it "fetches from ENV" do store = described_class.new(store: {"FOO" => "bar"}) expect(store.fetch("FOO")).to eq("bar") end it "capitalizes name" do store = described_class.new(store: {"FOO" => "bar"}) expect(store.fetch("foo")).to eq("bar") end it "coerces name to string" do store = described_class.new(store: {"FOO" => "bar"}) expect(store.fetch(:foo)).to eq("bar") end it "returns default when value is not found" do store = described_class.new(store: {"FOO" => "bar"}) expect(store.fetch("BAZ", "qux")).to eq("qux") end it "returns the block execution when value is not found" do store = described_class.new(store: {"FOO" => "bar"}) expect(store.fetch("BAZ") { "qux" }).to eq("qux") # rubocop:disable Style/RedundantFetchBlock end it "raises KeyError when value is not found and no default is given" do store = described_class.new(store: {"FOO" => "bar"}) expect { store.fetch("BAZ") }.to raise_error(KeyError) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/extensions/view/context_spec.rb
spec/unit/hanami/extensions/view/context_spec.rb
require "hanami/view" require "hanami/view/context" require "hanami/extensions/view/context" RSpec.describe(Hanami::View::Context) do subject(:context) { described_class.new(**args) } let(:args) { {} } describe "#assets" do context "assets given" do let(:args) { {assets: assets} } let(:assets) { double(:assets) } it "returns the assets" do expect(context.assets).to be assets end end context "no assets given" do it "raises a Hanami::ComponentLoadError" do expect { context.assets }.to raise_error Hanami::ComponentLoadError end end end describe "#request" do context "request given" do let(:args) { {request: request} } let(:request) { double(:request) } it "returns the request" do expect(context.request).to be request end end context "no request given" do it "raises a Hanami::ComponentLoadError" do expect { context.request }.to raise_error Hanami::ComponentLoadError end end end describe "#routes" do context "routes given" do let(:args) { {routes: routes} } let(:routes) { double(:routes) } it "returns the routes" do expect(context.routes).to be routes end end context "no routes given" do it "raises a Hanami::ComponentLoadError" do expect { context.routes }.to raise_error Hanami::ComponentLoadError end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/providers/db/config_spec.rb
spec/unit/hanami/providers/db/config_spec.rb
# frozen_string_literal: true require "dry/system" require "hanami/providers/db" RSpec.describe "Hanami::Providers::DB.config", :app_integration do subject(:config) { provider.source.config } let(:provider) { Hanami.app.prepare Hanami.app.configure_provider(:db) Hanami.app.container.providers[:db] } before do module TestApp class App < Hanami::App end end end describe "#adapter" do it "adds an adapter" do expect { config.adapter(:yaml) } .to change { config.adapters.to_h } .to hash_including(:yaml) end it "yields the adapter for configuration" do expect { |b| config.adapter(:yaml, &b) } .to yield_with_args(an_instance_of(Hanami::Providers::DB::Adapter)) end end describe "adapters" do subject(:adapter) { config.adapter(:yaml) } describe "#plugin" do it "adds a plugin without a block" do expect { adapter.plugin relations: :foo } .to change { adapter.plugins } .to [[{relations: :foo}, nil]] end it "adds a plugin with a block" do block = -> plugin_config { } expect { adapter.plugin(relations: :foo, &block) } .to change { adapter.plugins } .to [[{relations: :foo}, block]] end end describe "#plugins" do it "can be cleared" do adapter.plugin relations: :foo expect { adapter.plugins.clear } .to change { adapter.plugins } .to [] end end describe "#gateway_cache_keys" do it "includes the configured extensions" do expect(adapter.gateway_cache_keys).to eq({}) end end describe "#gateway_options" do specify do expect(adapter.gateway_options).to eq({}) end end describe "#clear" do it "clears previously configured plugins" do adapter.plugin relations: :foo expect { adapter.clear }.to change { adapter.plugins }.to([]) end end describe ":sql adapter" do subject(:adapter) { config.adapter(:sql) } describe "#extension" do it "adds an extension" do adapter.clear expect { adapter.extension :foo } .to change { adapter.extensions } .to [:foo] end it "adds multiple extensions" do adapter.clear expect { adapter.extension :foo, :bar } .to change { adapter.extensions } .to [:foo, :bar] end end describe "#extensions" do it "can be cleareed" do adapter.extension :foo expect { adapter.extensions.clear } .to change { adapter.extensions } .to [] end end describe "#gateway_cache_keys" do it "includes the configured extensions" do adapter.clear adapter.extension :foo, :bar expect(adapter.gateway_cache_keys).to eq(extensions: [:foo, :bar]) end end describe "#gateway_options" do it "includes the configured extensions" do adapter.clear adapter.extension :foo, :bar expect(adapter.gateway_options).to eq(extensions: [:foo, :bar]) end end describe "#clear" do it "clears previously configured plugins and extensions" do adapter.plugin relations: :foo adapter.extension :foo expect { adapter.clear } .to change { adapter.plugins }.to([]) .and change { adapter.extensions }.to([]) end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/providers/db/config/gateway_spec.rb
spec/unit/hanami/providers/db/config/gateway_spec.rb
# frozen_string_literal: true require "dry/system" require "hanami/providers/db" RSpec.describe "Hanami::Providers::DB / Config / Gateway config", :app_integration do subject(:config) { provider.source.config } let(:provider) { Hanami.app.prepare Hanami.app.configure_provider(:db) Hanami.app.container.providers[:db] } before do module TestApp class App < Hanami::App end end end describe "sql adapter" do before do config.adapter(:sql).configure_for_database("sqlite::memory") end describe "connection_options" do let(:default) { config.gateway(:default) } it "merges kwargs into connection_options configuration" do expect { default.connection_options(timeout: 10_000) } .to change { default.connection_options }.from({}).to({timeout: 10_000}) end it "sets options per-gateway" do other = config.gateway(:other) expect { default.connection_options(timeout: 10_000) } .to_not change { other.connection_options } end it "is reflected in Gateway#cache_keys" do default.adapter(:sql) {} expect { default.connection_options(timeout: 10_000) } .to change { default.cache_keys } end end describe "options" do it "combines connection_options with adapter.gateway_options" do config.gateway :default do |gw| gw.connection_options foo: "bar" gw.adapter :sql do |a| a.skip_defaults a.extension :baz, :quux end end expect(config.gateway(:default).options) .to include(foo: "bar", extensions: [:baz, :quux]) end it "ignores conflicting keys from connection_options" do config.gateway :default do |gw| gw.connection_options extensions: "foo" gw.adapter(:sql) { _1.skip_defaults } end expect(config.gateway(:default).options).to eq({extensions: []}) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/providers/db/config/default_config_spec.rb
spec/unit/hanami/providers/db/config/default_config_spec.rb
# frozen_string_literal: true require "dry/system" require "hanami/providers/db" RSpec.describe "Hanami::Providers::DB / Config / Default config", :app_integration do subject(:config) { provider.source.config } let(:provider) { Hanami.app.prepare Hanami.app.configure_provider(:db) Hanami.app.container.providers[:db] } before do module TestApp class App < Hanami::App end end end specify %(relations_path = "relations") do expect(config) end describe "sql adapter" do before do skip_defaults if respond_to?(:skip_defaults) config.adapter(:sql).configure_for_database("mysql://localhost/test_app_development") end describe "plugins" do specify do expect(config.adapter(:sql).plugins).to match [ [{relations: :instrumentation}, instance_of(Proc)], [{relations: :auto_restrictions}, nil], ] end describe "skipping defaults" do def skip_defaults config.adapter(:sql).skip_defaults :plugins end it "configures no plugins" do expect(config.adapter(:sql).plugins).to eq [] end end end describe "extensions" do specify do expect(config.adapter(:sql).extensions).to eq [ :caller_logging, :error_sql, :sql_comments ] end describe "skipping defaults" do def skip_defaults config.adapter(:sql).skip_defaults :extensions end it "configures no extensions" do expect(config.adapter(:sql).extensions).to eq [] end end end describe "skipping all defaults" do def skip_defaults config.adapter(:sql).skip_defaults end it "configures no plugins or extensions" do expect(config.adapter(:sql).plugins).to eq [] expect(config.adapter(:sql).extensions).to eq [] end end end describe "sql adapter for postgres" do before do config.adapter(:sql).configure_for_database("postgresql://localhost/test_app_development") end specify "extensions" do expect(config.adapters[:sql].extensions).to eq [ :caller_logging, :error_sql, :sql_comments, :pg_array, :pg_enum, :pg_json, :pg_range ] end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/slices_spec.rb
spec/unit/hanami/config/slices_spec.rb
# frozen_string_literal: true require "dry/inflector" require "hanami/config" require "hanami/slice_name" RSpec.describe Hanami::Config, "#slices" do subject(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { Hanami::SliceName.new(double(name: "MyApp::App"), inflector: Dry::Inflector.new) } subject(:slices) { config.slices } before do @orig_env = ENV.to_h end after do ENV.replace(@orig_env) end it "is nil by default" do is_expected.to be nil end it "defaults to the HANAMI_LOAD_SLICES env var, separated by commas" do ENV["HANAMI_SLICES"] = "main,admin" is_expected.to eq %w[main admin] end it "strips spaces from HANAMI_LOAD_SLICES env var entries" do ENV["HANAMI_SLICES"] = "main, admin" is_expected.to eq %w[main admin] end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/console_spec.rb
spec/unit/hanami/config/console_spec.rb
# frozen_string_literal: true require "hanami/config" RSpec.describe Hanami::Config, "#console" do let(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { "MyApp::App" } subject(:console) { config.console } it "is a full console configuration" do is_expected.to be_an_instance_of(Hanami::Config::Console) is_expected.to respond_to(:engine) is_expected.to respond_to(:include) is_expected.to respond_to(:extensions) end it "can be finalized" do is_expected.to respond_to(:finalize!) end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/inflector_spec.rb
spec/unit/hanami/config/inflector_spec.rb
# frozen_string_literal: true require "hanami/config" RSpec.describe Hanami::Config do subject(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { "MyApp::app" } describe "inflector" do it "defaults to a Dry::Inflector instance" do expect(config.inflector).to be_kind_of(Dry::Inflector) end it "can be replaced with another inflector" do new_inflector = double(:inflector) expect { config.inflector = new_inflector } .to change { config.inflector } .to new_inflector end end describe "inflections" do it "configures a new inflector with the given inflections" do expect(config.inflector.pluralize("hanami")).to eq("hanamis") config.inflections do |i| i.uncountable("hanami") end expect(config.inflector).to be_kind_of(Dry::Inflector) expect(config.inflector.pluralize("hanami")).to eq("hanami") end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/router_spec.rb
spec/unit/hanami/config/router_spec.rb
# frozen_string_literal: true require "hanami/config" RSpec.describe Hanami::Config, "#router" do let(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { "MyApp::app" } subject(:router) { config.router } context "hanami-router is bundled" do it "is a full router configuration" do is_expected.to be_an_instance_of(Hanami::Config::Router) is_expected.to respond_to(:resolver) end it "loads the middleware stack" do subject expect(config.middleware_stack).not_to be_nil end it "can be finalized" do is_expected.to respond_to(:finalize!) end end context "hanami-router is not bundled" do before do allow(Hanami).to receive(:bundled?).and_call_original allow(Hanami).to receive(:bundled?).with("hanami-router").and_return(false) end it "does not expose any settings" do is_expected.to be_an_instance_of(Hanami::Config::NullConfig) is_expected.not_to respond_to(:resolver) end it "can be finalized" do is_expected.to respond_to(:finalize!) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/render_detailed_errors_spec.rb
spec/unit/hanami/config/render_detailed_errors_spec.rb
# frozen_string_literal: true require "dry/inflector" RSpec.describe Hanami::Config, "#render_detailed_errors" do let(:config) { described_class.new(app_name: app_name, env: env) } let(:app_name) { Hanami::SliceName.new(double(name: "MyApp::App"), inflector: Dry::Inflector.new) } subject(:render_detailed_errors) { config.render_detailed_errors } context "development mode" do let(:env) { :development } it { is_expected.to be true } end context "test mode" do let(:env) { :test } it { is_expected.to be false } end context "production mode" do let(:env) { :production } it { is_expected.to be false } end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/actions_spec.rb
spec/unit/hanami/config/actions_spec.rb
# frozen_string_literal: true require "hanami/config" require "hanami/action" RSpec.describe Hanami::Config, "#actions" do let(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { "MyApp::app" } subject(:actions) { config.actions } context "hanami-controller is bundled" do it "is a full actions config" do is_expected.to be_an_instance_of(Hanami::Config::Actions) is_expected.to respond_to(:format) end it "configures base action settings" do expect { actions.public_directory = "pub" } .to change { actions.public_directory } .to end_with("pub") end it "configures base actions settings using custom methods" do expect { actions.formats.register(:json, "app/json") } .to change { actions.formats.mapping } .to include(json: have_attributes(media_type: "app/json")) end it "can be finalized" do is_expected.to respond_to(:finalize!) end end context "hanami-controller is not bundled" do before do allow(Hanami).to receive(:bundled?).and_call_original expect(Hanami).to receive(:bundled?).with("hanami-controller").and_return(false) end it "does not expose any settings" do is_expected.to be_an_instance_of(Hanami::Config::NullConfig) is_expected.not_to respond_to(:default_response_format) is_expected.not_to respond_to(:default_response_format=) end it "can be finalized" do is_expected.to respond_to(:finalize!) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/logger_spec.rb
spec/unit/hanami/config/logger_spec.rb
# frozen_string_literal: true require "hanami/config/logger" require "hanami/slice_name" require "dry/inflector" require "logger" require "stringio" RSpec.describe Hanami::Config::Logger do subject do described_class.new(app_name: app_name, env: env) end let(:app_name) do Hanami::SliceName.new(double(name: "MyApp::app"), inflector: -> { Dry::Inflector.new }) end let(:env) { :development } describe "#level" do it "defaults to :debug" do expect(subject.level).to eq(:debug) end context "when :production environment" do let(:env) { :production } it "returns :info" do expect(subject.level).to eq(:info) end end end describe "#level=" do it "a value" do expect { subject.level = :warn } .to change { subject.level } .to(:warn) end end describe "#stream" do it "defaults to $stdout" do expect(subject.stream).to eq($stdout) end context "when :test environment" do let(:env) { :test } it "returns a file" do expected = File.join("log", "test.log") expect(subject.stream).to eq(expected) end end end describe "#stream=" do it "accepts a path to a file" do expect { subject.stream = File::NULL } .to change { subject.stream } .to(File::NULL) end it "accepts a IO object" do stream = StringIO.new expect { subject.stream = stream } .to change { subject.stream } .to(stream) end end describe "#formatter" do it "defaults to :string" do expect(subject.formatter).to eq(:string) end context "when :production environment" do let(:env) { :production } it "returns :json" do expect(subject.formatter).to eq(:json) end end end describe "#formatter=" do it "accepts a formatter" do expect { subject.formatter = :json } .to change { subject.formatter } .to(:json) end end describe "#template" do it "defaults to :details" do expect(subject.template).to be(:details) end end describe "#template=" do it "accepts a value" do expect { subject.template = "%<message>s" } .to change { subject.template } .to("%<message>s") end end describe "#filters" do it "defaults to a standard array of sensitive param names" do expect(subject.filters).to include(*%w[_csrf password password_confirmation]) end it "can have other params names added" do expect { subject.filters << "secret" } .to change { subject.filters } .to array_including("secret") expect { subject.filters += ["yet", "another"] } .to change { subject.filters } .to array_including(["yet", "another"]) end it "can be changed to another array" do expect { subject.filters = ["secret"] } .to change { subject.filters } .to ["secret"] end end describe "#options" do it "defaults to empty hash" do expect(subject.options).to eq({}) end end describe "#options=" do it "accepts value" do subject.options = expected = {rotate: "daily"} expect(subject.options).to eq(expected) end end end RSpec.describe Hanami::Config do subject(:config) { described_class.new(app_name: app_name, env: env) } let(:app_name) do Hanami::SliceName.new(double(name: "SOS::app"), inflector: -> { Dry::Inflector.new }) end let(:env) { :development } describe "#logger" do before do config.inflections do |inflections| inflections.acronym "SOS" end config.logger.finalize! end describe "#app_name" do it "defaults to Hanami::Config#app_name" do expect(config.logger.app_name).to eq(config.app_name) end end end describe "#logger_instance" do it "defaults to using Dry::Logger, based on the default logger settings" do expect(config.logger_instance).to be_a(Dry::Logger::Dispatcher) expect(config.logger_instance.level).to eq Logger::DEBUG end it "can be changed to a pre-initialized instance via #logger=" do logger_instance = Object.new expect { config.logger = logger_instance } .to change { config.logger_instance } .to logger_instance end context "unrecognized :env" do let(:env) { :staging } it "provides a fail-safe configuration" do expect { config.logger_instance }.to_not raise_error expect(config.logger_instance).to be_a(Dry::Logger::Dispatcher) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/base_url_spec.rb
spec/unit/hanami/config/base_url_spec.rb
# frozen_string_literal: true require "hanami/config" require "uri" RSpec.describe Hanami::Config, "base_url" do subject(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { "MyApp::app" } it "defaults to a URI of 'http://0.0.0.0:2300'" do expect(config.base_url).to eq URI("http://0.0.0.0:2300") end it "can be changed to another URI via a string" do expect { config.base_url = "http://example.com" } .to change { config.base_url } .to(URI("http://example.com")) end it "can be changed to another URI object" do expect { config.base_url = URI("http://example.com") } .to change { config.base_url } .to(URI("http://example.com")) end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/views_spec.rb
spec/unit/hanami/config/views_spec.rb
# frozen_string_literal: true require "hanami/config" require "saharspec/matchers/dont" RSpec.describe Hanami::Config, "#views" do let(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { "MyApp::app" } subject(:views) { config.views } context "hanami-view is bundled" do it "exposes Hanami::Views's app config" do is_expected.to be_an_instance_of(Hanami::Config::Views) is_expected.to respond_to(:finalize!) is_expected.to respond_to(:layouts_dir) is_expected.to respond_to(:layouts_dir=) end it "includes base view config" do expect(views).to respond_to(:paths) expect(views).to respond_to(:paths=) end it "does not include the inflector setting" do expect(views).not_to respond_to(:inflector) expect(views).not_to respond_to(:inflector=) end it "preserves default values from the base view config" do expect(views.layouts_dir).to eq Hanami::View.config.layouts_dir end it "allows settings to be configured independently of the base view config" do expect { views.layouts_dir = "custom_layouts" } .to change { views.layouts_dir }.to("custom_layouts") .and(dont.change { Hanami::View.config.layouts_dir }) end describe "specialised default values" do describe "layout" do it 'is "app"' do expect(views.layout).to eq "app" end end end describe "finalized config" do before do views.finalize! end it "is frozen" do expect(views).to be_frozen end it "does not allow changes to base view settings" do expect { views.paths = [] }.to raise_error(Dry::Configurable::FrozenConfigError) end end end context "hanami-view is not bundled" do before do allow(Hanami).to receive(:bundled?).and_call_original expect(Hanami).to receive(:bundled?).with("hanami-view").and_return(false) end it "does not expose any settings" do is_expected.to be_an_instance_of(Hanami::Config::NullConfig) is_expected.not_to respond_to(:layouts_dir) is_expected.not_to respond_to(:layouts_dir=) end it "can be finalized" do is_expected.to respond_to(:finalize!) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/render_errors_spec.rb
spec/unit/hanami/config/render_errors_spec.rb
# frozen_string_literal: true require "dry/inflector" RSpec.describe Hanami::Config, "#render_errors" do let(:config) { described_class.new(app_name: app_name, env: env) } let(:app_name) { Hanami::SliceName.new(double(name: "MyApp::App"), inflector: Dry::Inflector.new) } subject(:render_errors) { config.render_errors } context "development mode" do let(:env) { :development } it { is_expected.to be false } end context "test mode" do let(:env) { :test } it { is_expected.to be false } end context "production mode" do let(:env) { :production } it { is_expected.to be true } end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/db_spec.rb
spec/unit/hanami/config/db_spec.rb
# frozen_string_literal: true require "hanami/config" RSpec.describe Hanami::Config, "#db" do let(:config) { described_class.new(app_name: app_name, env: :development) } let(:app_name) { "MyApp::App" } subject(:db) { config.db } context "hanami-router is bundled" do it "is a full router configuration" do is_expected.to be_an_instance_of(Hanami::Config::DB) is_expected.to respond_to(:import_from_parent) end it "can be finalized" do is_expected.to respond_to(:finalize!) end end context "hanami-db is not bundled" do before do allow(Hanami).to receive(:bundled?).and_call_original allow(Hanami).to receive(:bundled?).with("hanami-db").and_return(false) end it "does not expose any settings" do is_expected.to be_an_instance_of(Hanami::Config::NullConfig) is_expected.not_to respond_to(:import_from_parent) end it "can be finalized" do is_expected.to respond_to(:finalize!) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/actions/cookies_spec.rb
spec/unit/hanami/config/actions/cookies_spec.rb
# frozen_string_literal: true require "hanami/config/actions" RSpec.describe Hanami::Config::Actions, "#cookies" do let(:config) { described_class.new } subject(:cookies) { config.cookies } context "default config" do it "is enabled" do expect(cookies).to be_enabled end it "is an empty hash" do expect(cookies.to_h).to eq({}) end end context "options given" do before do config.cookies = {max_age: 300} end it "is enabled" do expect(cookies).to be_enabled end it "returns the given options" do expect(cookies.to_h).to eq(max_age: 300) end end context "nil value given" do before do config.cookies = nil end it "is not enabled" do expect(cookies).not_to be_enabled end it "returns an empty hash" do expect(cookies.to_h).to eq({}) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/actions/csrf_protection_spec.rb
spec/unit/hanami/config/actions/csrf_protection_spec.rb
# frozen_string_literal: true require "hanami/config/actions" RSpec.describe Hanami::Config::Actions, "#csrf_protection" do let(:app_config) { Hanami::Config.new(app_name: "MyApp::App", env: :development) } let(:config) { app_config.actions } subject(:value) { config.csrf_protection } context "non-finalized config" do it "returns a default of nil" do is_expected.to be_nil end it "can be explicitly enabled" do config.csrf_protection = true is_expected.to be true end it "can be explicitly disabled" do config.csrf_protection = false is_expected.to be false end end context "finalized config" do context "sessions enabled" do before do config.sessions = :cookie, {secret: "abc"} app_config.finalize! end it "is true" do is_expected.to be true end context "explicitly disabled" do before do config.csrf_protection = false end it "is false" do is_expected.to be false end end end context "sessions not enabled" do before do app_config.finalize! end it "is true" do is_expected.to be false end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/actions/default_values_spec.rb
spec/unit/hanami/config/actions/default_values_spec.rb
# frozen_string_literal: true require "hanami/config/actions" RSpec.describe Hanami::Config::Actions, "default values" do let(:app_config) { Hanami::Config.new(app_name: "MyApp::App", env: :development) } subject(:config) { app_config.actions } describe "sessions" do specify { expect(config.sessions).not_to be_enabled } end describe "name_inference_base" do specify { expect(config.name_inference_base).to eq "actions" } end describe "view_name_inferrer" do specify { expect(config.view_name_inferrer).to eq Hanami::Slice::ViewNameInferrer } end describe "view_name_inference_base" do specify { expect(config.view_name_inference_base).to eq "views" } end describe "new default values applied to base action settings" do describe "content_security_policy" do specify { expect(config.content_security_policy).to be_kind_of(Hanami::Config::Actions::ContentSecurityPolicy) } end describe "default_headers" do specify { app_config.finalize! expect(config.default_headers).to eq( "X-Frame-Options" => "DENY", "X-Content-Type-Options" => "nosniff", "X-XSS-Protection" => "1; mode=block", "Content-Security-Policy" => config.content_security_policy.to_s ) } end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/actions/sessions_spec.rb
spec/unit/hanami/config/actions/sessions_spec.rb
# frozen_string_literal: true require "hanami/config/actions" RSpec.describe Hanami::Config::Actions, "#sessions" do let(:config) { described_class.new } subject(:sessions) { config.sessions } context "no session config specified" do it "is not enabled" do expect(sessions).not_to be_enabled end it "returns nil storage" do expect(sessions.storage).to be_nil end it "returns empty options" do expect(sessions.options).to eq [] end it "returns no session middleware" do expect(sessions.middleware).to eq [] end end context "valid session config provided" do before do config.sessions = :cookie, {secret: "abc"} end it "is enabled" do expect(sessions).to be_enabled end it "returns the given storage" do expect(sessions.storage).to eq :cookie end it "returns the given options" do expect(sessions.options).to eq [secret: "abc"] end it "returns an array of middleware classes and options" do expect(sessions.middleware).to eq [Rack::Session::Cookie, {secret: "abc"}] end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/config/actions/content_security_policy_spec.rb
spec/unit/hanami/config/actions/content_security_policy_spec.rb
# frozen_string_literal: true require "hanami/config/actions" RSpec.describe Hanami::Config::Actions, "#content_security_policy" do let(:app_config) { Hanami::Config.new(app_name: "MyApp::App", env: :development) } let(:config) { app_config.actions } subject(:content_security_policy) { config.content_security_policy } context "no CSP config specified" do it "has defaults" do expect(content_security_policy[:base_uri]).to eq("'self'") expected = [ %(base-uri 'self'), %(child-src 'self'), %(connect-src 'self'), %(default-src 'none'), %(font-src 'self'), %(form-action 'self'), %(frame-ancestors 'self'), %(frame-src 'self'), %(img-src 'self' https: data:), %(media-src 'self'), %(object-src 'none'), %(script-src 'self'), %(style-src 'self' 'unsafe-inline' https:) ].join(";") expect(content_security_policy.to_s).to eq(expected) expect(content_security_policy.nonce?).to be(false) end end context "CSP settings specified" do let(:cdn_url) { "https://assets.hanamirb.test" } it "appends to default values" do content_security_policy[:script_src] += " #{cdn_url}" expect(content_security_policy[:script_src]).to eq("'self' #{cdn_url}") expect(content_security_policy.to_s).to match("'self' #{cdn_url}") end it "overrides default values" do content_security_policy[:style_src] = cdn_url expect(content_security_policy[:style_src]).to eq(cdn_url) expect(content_security_policy.to_s).to match(cdn_url) end it "nullifies value" do content_security_policy[:object_src] = nil expect(content_security_policy[:object_src]).to be(nil) expect(content_security_policy.to_s).to match("object-src ;") end it "deletes key" do content_security_policy.delete(:object_src) expect(content_security_policy[:object_src]).to be(nil) expect(content_security_policy.to_s).to_not match("object-src") end it "adds a custom key" do content_security_policy[:a_custom_key] = "foo" expect(content_security_policy[:a_custom_key]).to eq("foo") expect(content_security_policy.to_s).to match("a-custom-key foo") end it "uses 'nonce' in value" do content_security_policy[:javascript_src] = "'self' 'nonce'" expect(content_security_policy.nonce?).to be(true) end end context "with CSP enabled" do it "sets default header" do app_config.finalize! expect(config.default_headers.fetch("Content-Security-Policy")).to eq(content_security_policy.to_s) end end context "with CSP disabled" do it "doesn't set default header" do config.content_security_policy = false app_config.finalize! expect(config.default_headers.key?("Content-Security-Policy")).to be(false) end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/router/errors/not_found_error_spec.rb
spec/unit/hanami/router/errors/not_found_error_spec.rb
# frozen_string_literal: true require "hanami/router" require "hanami/extensions/router/errors" RSpec.describe(Hanami::Router::NotFoundError) do subject(:error) { described_class.new(env) } let(:env) { Rack::MockRequest.env_for("http://example.com/example", method: "GET") } it "is a Hanami::Router::Error" do expect(error.class).to be < Hanami::Router::Error end it "returns a relevant message" do expect(error.to_s).to eq "No route found for GET /example" end it "returns the env" do expect(error.env).to be env end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/router/errors/not_allowed_error_spec.rb
spec/unit/hanami/router/errors/not_allowed_error_spec.rb
# frozen_string_literal: true require "hanami/router" require "hanami/extensions/router/errors" RSpec.describe(Hanami::Router::NotAllowedError) do subject(:error) { described_class.new(env, allowed_methods) } let(:env) { Rack::MockRequest.env_for("http://example.com/example", method: "POST") } let(:allowed_methods) { ["GET", "HEAD"] } it "is a Hanami::Router::Error" do expect(error.class).to be < Hanami::Router::Error end it "returns a relevant message" do expect(error.to_s).to eq "Only GET, HEAD requests are allowed at /example" end it "returns the env" do expect(error.env).to be env end it "returns the allowed methods" do expect(error.allowed_methods).to be allowed_methods end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/spec/unit/hanami/web/rack_logger_spec.rb
spec/unit/hanami/web/rack_logger_spec.rb
# frozen_string_literal: true require "hanami/web/rack_logger" require "dry/logger" require "stringio" require "rack/mock" RSpec.describe Hanami::Web::RackLogger do subject { described_class.new(logger) } let(:logger) do Dry.Logger( app_name, stream: stream, level: :debug, filters: filters, formatter: :rack, template: "[%<progname>s] [%<severity>s] [%<time>s] %<message>s" ) end let(:stream) { StringIO.new } let(:filters) { ["user.password"] } let(:app_name) { "my_app" } describe "#initialize" do it "returns an instance of #{described_class}" do expect(subject).to be_kind_of(described_class) end end describe "#log_request" do it "logs current request" do time = Time.parse("2022-02-04 11:38:25.218816 +0100") expect(Time).to receive(:now).at_least(:once).and_return(time) path = "/users" ip = "127.0.0.1" status = 200 elapsed = 0.0001 content_length = 23 verb = "POST" env = Rack::MockRequest.env_for(path, method: verb) env["CONTENT_LENGTH"] = content_length env["REMOTE_ADDR"] = ip params = {"user" => {"password" => "secret"}} env["router.params"] = params subject.log_request(env, status, elapsed) stream.rewind actual = stream.read if RUBY_VERSION < "3.4" expect(actual).to eql(<<~LOG) [#{app_name}] [INFO] [#{time}] #{verb} #{status} #{elapsed}µs #{ip} #{path} #{content_length} {"user"=>{"password"=>"[FILTERED]"}} LOG else expect(actual).to eql(<<~LOG) [#{app_name}] [INFO] [#{time}] #{verb} #{status} #{elapsed}µs #{ip} #{path} #{content_length} {"user" => {"password" => "[FILTERED]"}} LOG end end context "ip" do it "takes into account HTTP proxy forwarding" do env = Rack::MockRequest.env_for("/") env["REMOTE_ADDR"] = remote = "127.0.0.1" env["HTTP_X_FORWARDED_FOR"] = forwarded = "::1" subject.log_request(env, 200, 0.1) stream.rewind actual = stream.read expect(actual).to include(forwarded) expect(actual).to_not include(remote) end end context "path prefix" do it "logs full referenced relative path" do env = Rack::MockRequest.env_for(path = "/users") env["SCRIPT_NAME"] = script_name = "/v1" subject.log_request(env, 200, 0.1) stream.rewind actual = stream.read expect(actual).to include(script_name + path) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami.rb
lib/hanami.rb
# frozen_string_literal: true require "pathname" require "zeitwerk" require_relative "hanami/constants" # A complete web framework for Ruby # # @since 0.1.0 # # @see http://hanamirb.org module Hanami @_mutex = Mutex.new @_bundled = {} # @api private # @since 2.0.0 def self.loader @loader ||= Zeitwerk::Loader.for_gem.tap do |loader| loader.inflector.inflect "db" => "DB" loader.inflector.inflect "db_logging" => "DBLogging" loader.inflector.inflect "slice_configured_db_operation" => "SliceConfiguredDBOperation" loader.inflector.inflect "sql_adapter" => "SQLAdapter" gem_lib = loader.dirs.first loader.ignore( "#{gem_lib}/hanami/{constants,boot,errors,extensions/router/errors,prepare,rake_tasks,setup}.rb", # Ignore conditionally-loaded classes dependent on gems that may not be included in the # user's Gemfile "#{gem_lib}/hanami/config/{assets,router,views}.rb", "#{gem_lib}/hanami/slice/router.rb", "#{gem_lib}/hanami/slice/routing/resolver.rb", "#{gem_lib}/hanami/slice/routing/middleware/stack.rb", "#{gem_lib}/hanami/extensions/**/*" ) unless Hanami.bundled?("hanami-router") loader.ignore("#{gem_lib}/hanami/routes.rb") end end end # Finds and loads the Hanami app file (`config/app.rb`). # # Raises an exception if the app file cannot be found. # # @return [app] the loaded app class # # @api public # @since 2.0.0 def self.setup(raise_exception: true) return app if app? app_path = self.app_path if app_path prepare_load_path require(app_path.to_s) app elsif raise_exception raise( AppLoadError, "Could not locate your Hanami app file.\n\n" \ "Your app file should be at `config/app.rb` in your project's root directory." ) end end # Prepare the load path as early as possible (based on the default root inferred from the location # of `config/app.rb`), so `require` can work at the top of `config/app.rb`. This may be useful # when external classes are needed for configuring certain aspects of the app. # # @api private # @since 2.0.0 private_class_method def self.prepare_load_path lib_path = app_path&.join("..", "..", LIB_DIR) if lib_path&.directory? path = lib_path.realpath.to_s $LOAD_PATH.prepend(path) unless $LOAD_PATH.include?(path) end lib_path end # Returns the Hamami app class. # # To ensure your Hanami app is loaded, run {.setup} (or `require "hanami/setup"`) first. # # @return [Hanami::App] the app class # # @raise [AppLoadError] if the app has not been loaded # # @see .setup # # @api public # @since 2.0.0 def self.app @_mutex.synchronize do unless defined?(@_app) raise AppLoadError, "Hanami.app is not yet configured. " \ "You may need to `require \"hanami/setup\"` to load your config/app.rb file." end @_app end end # Returns true if the Hanami app class has been loaded. # # @return [Boolean] # # @api public # @since 2.0.0 def self.app? instance_variable_defined?(:@_app) end # @api private # @since 2.0.0 def self.app=(klass) @_mutex.synchronize do if instance_variable_defined?(:@_app) raise AppLoadError, "Hanami.app is already configured." end @_app = klass unless klass.name.nil? end end # Finds and returns the absolute path for the Hanami app file (`config/app.rb`). # # Searches within the given directory, then searches upwards through parent directories until the # app file can be found. # # @param dir [String, Pathname] The directory from which to start searching. Defaults to the # current directory. # # @return [Pathname, nil] the app file path, or nil if not found. # # @api public # @since 2.0.0 def self.app_path(dir = Dir.pwd) dir = Pathname(dir).expand_path path = dir.join(APP_PATH) if path.file? path elsif !dir.root? app_path(dir.parent) end end # Returns the Hanami app environment as determined from the environment. # # Checks the following environment variables in order: # # - `HANAMI_ENV` # - `APP_ENV` # - `RACK_ENV` # # Defaults to `:development` if no environment variable is set. # # @example # Hanami.env # => :development # # @return [Symbol] the environment name # # @api public # @since 2.0.0 def self.env(e: ENV) (e["HANAMI_ENV"] || e["APP_ENV"] || e["RACK_ENV"] || :development).to_sym end # Returns true if {.env} matches any of the given names # # @example # Hanami.env # => :development # Hanami.env?(:development, :test) # => true # # @param names [Array<Symbol>] the environment names to check # # @return [Boolean] # # @api public # @since 2.0.0 def self.env?(*names) names.map(&:to_sym).include?(env) end # Returns the app's logger. # # Direct global access to the logger via this method is not recommended. Instead, consider # accessing the logger via the app or slice container, in most cases as an dependency using the # `Deps` mixin. # # @example # # app/my_component.rb # # module MyApp # class MyComponent # include Deps["logger"] # # def some_method # logger.info("hello") # end # end # end # # @return [Dry::Logger::Dispatcher] # # @api public # @since 1.0.0 def self.logger app[:logger] end # Prepares the Hanami app. # # @see App::ClassMethods#prepare # # @api public # @since 2.0.0 def self.prepare app.prepare end # Boots the Hanami app. # # @see App::ClassMethods#boot # # @api public # @since 2.0.0 def self.boot app.boot end # Shuts down the Hanami app. # # @see App::ClassMethods#shutdown # # @api public # @since 2.0.0 def self.shutdown app.shutdown end # @api private # @since 2.0.0 def self.bundled?(gem_name) @_mutex.synchronize do @_bundled[gem_name] ||= begin gem(gem_name) rescue Gem::LoadError false end end end # Returns an array of bundler group names to be eagerly loaded by hanami-cli and other CLI # extensions. # # @api private # @since 2.0.0 def self.bundler_groups [:plugins] end loader.setup require_relative "hanami/errors" require_relative "hanami/extensions" end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/rake_tasks.rb
lib/hanami/rake_tasks.rb
# frozen_string_literal: true require "hanami/cli" Hanami::CLI::RakeTasks.register_tasks do desc "Load the app environment" task :environment do require "hanami/prepare" end # Ruby ecosystem compatibility # # Most of the hosting SaaS automatic tasks are designed after Ruby on Rails. # They expect the following Rake tasks to be present: # # * db:migrate # * assets:precompile # # See https://github.com/heroku/heroku-buildpack-ruby/issues/442 # # === # # These Rake tasks are **NOT** listed when someone runs `rake -T`, because we # want to encourage developers to use `hanami` CLI commands. # # In order to migrate the database or compile assets a developer should use: # # * hanami db migrate # * hanami assets compile # # This is the preferred way to run Hanami command line tasks. # Please use them when you're in control of your deployment environment. # # If you're not in control and your deployment requires these "standard" # Rake tasks, they are here only to solve this specific problem. if Hanami.bundled?("hanami-db") namespace :db do task :migrate do Hanami::CLI::Commands::App::DB::Migrate.new.call end end end if Hanami.bundled?("hanami-assets") namespace :assets do task :precompile do Hanami::CLI::Commands::App::Assets::Compile.new.call end end end end Hanami::CLI::RakeTasks.install_tasks
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice.rb
lib/hanami/slice.rb
# frozen_string_literal: true require "zeitwerk" require "dry/system" require_relative "constants" require_relative "errors" module Hanami # A slice represents any distinct area of concern within an Hanami app. # # For smaller apps, a slice may encompass the whole app itself (see # {Hanami::App}), whereas larger apps may consist of many slices. # # Each slice corresponds a single module namespace and a single root directory of source # files for loading as components into its container. # # Each slice has its own config, and may optionally have its own settings, routes, as well as # other nested slices. # # Slices expect an Hanami app to be defined (which itself is a slice). They will initialize their # config as a copy of the app's, and will also configure certain components # # Slices must be _prepared_ and optionally _booted_ before they can be used (see # {ClassMethods.prepare} and {ClassMethods.boot}). A prepared slice will lazily load its # components and nested slices (useful for minimising initial load time), whereas a # booted slice will eagerly load all its components and nested slices, then freeze its # container. # # @since 2.0.0 class Slice @_mutex = Mutex.new # @api private def self.inherited(subclass) super subclass.extend(ClassMethods) @_mutex.synchronize do subclass.class_eval do @_mutex = Mutex.new @autoloader = Zeitwerk::Loader.new @container = Class.new(Dry::System::Container) end end end # rubocop:disable Metrics/ModuleLength module ClassMethods # Returns the slice's parent. # # For top-level slices defined in `slices/` or `config/slices/`, this will be the Hanami app # itself (`Hanami.app`). For nested slices, this will be the slice in which they were # registered. # # @return [Hanami::Slice] # # @see #register_slice # # @api public # @since 2.0.0 attr_reader :parent # Returns the slice's autoloader. # # Each slice has its own `Zeitwerk::Loader` autoloader instance, which is setup when the slice # is {#prepare prepared}. # # @return [Zeitwerk::Loader] # # @see https://github.com/fxn/zeitwerk # # @api public # @since 2.0.0 attr_reader :autoloader # Returns the slice's container. # # This is a `Dry::System::Container` that is already configured for the slice. # # In ordinary usage, you shouldn't need direct access the container at all, since the slice # provides its own methods for interacting with the container (such as {#[]}, {#keys}, {#key?} # {#register}, {#register_provider}, {#prepare}, {#start}, {#stop}). # # If you need to configure the container directly, use {#prepare_container}. # # @see https://dry-rb.org/gems/dry-system # # @api public # @since 2.0.0 attr_reader :container # Returns the Hanami app. # # @return [Hanami::App] # # @api public # @since 2.0.0 def app Hanami.app end # Returns true if the slice is Hanami.app # # @return [Boolean] # # @api public # @since 2.2.0 def app? eql?(app) end # Returns the slice's config. # # A slice's config is copied from the app config at time of first access. # # @return [Hanami::Config] # # @see App::ClassMethods.config # # @api public # @since 2.0.0 def config @config ||= app.config.dup.tap do |slice_config| # Unset config from app that does not apply to ordinary slices slice_config.root = nil end end # Evaluates the block for a given app environment only. # # If the given `env_name` matches {Hanami.env}, then the block will be evaluated in the # context of `self` (the slice) via `instance_eval`. The slice is also passed as the block's # optional argument. # # If the env does not match, then the block is not evaluated at all. # # @example # module MySlice # class Slice < Hanami::Slice # environment(:test) do # config.logger.level = :info # end # end # end # # @overload environment(env_name) # @param env_name [Symbol] the environment name # # @overload environment(env_name) # @param env_name [Symbol] the environment name # @yieldparam slice [self] the slice # # @return [self] # # @see Hanami.env # # @api public # @since 2.0.0 def environment(env_name, &block) instance_eval(&block) if env_name == config.env self end # Returns a {SliceName} for the slice, an object with methods returning the name of the slice # in various formats. # # @return [SliceName] # # @api public # @since 2.0.0 def slice_name @slice_name ||= SliceName.new(self, inflector: method(:inflector)) end # Returns the constant for the slice's module namespace. # # @example # MySlice::Slice.namespace # => MySlice # # @return [Module] the namespace module constant # # @see SliceName#namespace # # @api public # @since 2.0.0 def namespace slice_name.namespace end # Returns the slice's root, either the root as explicitly configured, or a default fallback of # the slice's name within the app's `slices/` dir. # # @return [Pathname] # # @see Config#root # # @api public # @since 2.0.0 def root # Provides a best guess for a root when it is not yet configured. # # This is particularly useful for user-defined slice classes that access `settings` inside # the class body (since the root needed to find the settings file). In this case, # `configuration.root` may be nil when `settings` is called, since the root is configured by # `SliceRegistrar#configure_slice` _after_ the class is loaded. # # In common cases, this best guess will be correct since most Hanami slices will be expected # to live in the app SLICES_DIR. For advanced cases, the correct slice root should be # explicitly configured at the beginning of the slice class body, before any calls to # `settings`. config.root || app.root.join(SLICES_DIR, slice_name.to_s) end # Returns the slice's root component directory, accounting for App as a special case. # # @return [Pathname] # # @api public # @since 2.2.0 def source_path app? ? root.join(APP_DIR) : root end # Returns the slice's root component directory, as a path relative to the app's root. # # @return [Pathname] # # @see #source_path # # @api public # @since 2.3.0 def relative_source_path source_path.relative_path_from(app.root) end # Returns the slice's configured inflector. # # Unless explicitly re-configured for the slice, this will be the app's inflector. # # @return [Dry::Inflector] # # @see Config#inflector # @see Config#inflections # # @api public # @since 2.0.0 def inflector config.inflector end # @overload prepare # Prepares the slice. # # This will define the slice's `Slice` and `Deps` constants, make all Ruby source files # inside the slice's root dir autoloadable, as well as lazily loadable as container # components. # # Call `prepare` when you want to access particular components within the slice while still # minimizing load time. Preparing slices is the approach taken when loading the Hanami # console or when running tests. # # @return [self] # # @see #boot # # @api public # @since 2.0.0 # # @overload prepare(provider_name) # Prepares a provider. # # This triggers the provider's `prepare` lifecycle step. # # @param provider_name [Symbol] the name of the provider to start # # @return [self] # # @api public # @since 2.0.0 def prepare(provider_name = nil) if provider_name container.prepare(provider_name) else prepare_slice end self end # Captures the given block to be called with the slice's container during the slice's # `prepare` step, after the slice has already configured the container. # # This is intended for advanced usage only and should not be needed for ordinary slice # configuration and usage. # # @example # module MySlice # class Slice < Hanami::Slice # prepare_container do |container| # # ... # end # end # end # # @yieldparam container [Dry::System::Container] the slice's container # # @return [self] # # @see #prepare # # @api public # @since 2.0.0 def prepare_container(&block) @prepare_container_block = block self end # Boots the slice. # # This will prepare the slice (if not already prepared), start each of its providers, register # all the slice's components from its Ruby source files, and import components from any other # slices. It will also boot any of the slice's own registered nested slices. It will then # freeze its container so no further components can be registered. # # Call `boot` if you want to fully load a slice and incur all load time up front, such as when # preparing an app to serve web requests. Booting slices is the approach taken when running # Hanami's standard Puma setup (see `config.ru`). # # @return [self] # # @see #prepare # # @api public # @since 2.0.0 def boot return self if booted? prepare container.finalize! slices.each(&:boot) @booted = true self end # Shuts down the slice's providers, as well as the providers in any nested slices. # # @return [self] # # @api public # @since 2.0.0 def shutdown slices.each(&:shutdown) container.shutdown! self end # Returns true if the slice has been prepared. # # @return [Boolean] # # @see #prepare # # @api public # @since 2.0.0 def prepared? !!@prepared end # Returns true if the slice has been booted. # # @return [Boolean] # # @see #boot # # @api public # @since 2.0.0 def booted? !!@booted end # Returns the slice's collection of nested slices. # # @return [SliceRegistrar] # # @see #register_slice # # @api public # @since 2.0.0 def slices @slices ||= SliceRegistrar.new(self) end # @overload register_slice(name, &block) # Registers a nested slice with the given name. # # This will define a new {Slice} subclass for the slice. If a block is given, it is passed # the class object, and will be evaluated in the context of the class like `class_eval`. # # @example # MySlice::Slice.register_slice do # # Configure the slice or do other class-level things here # end # # @param name [Symbol] the identifier for the slice to be registered # @yieldparam slice [Hanami::Slice] the newly defined slice class # # @overload register_slice(name, slice_class) # Registers a nested slice with the given name. # # The given `slice_class` will be registered as the slice. It must be a subclass of {Slice}. # # @param name [Symbol] the identifier for the slice to be registered # @param slice_class [Hanami::Slice] # # @return [slices] # # @see SliceRegistrar#register # # @api public # @since 2.0.0 def register_slice(...) slices.register(...) end # Registers a component in the slice's container. # # @overload register(key, object) # Registers the given object as the component. This same object will be returned whenever # the component is resolved. # # @param key [String] the component's key # @param object [Object] the object to register as the component # # @overload register(key, memoize: false, &block) # Registers the given block as the component. When the component is resolved, the return # value of the block will be returned. # # Since the block is not called until resolution-time, this is a useful way to register # components that have dependencies on other components in the container, which as yet may # be unavailable at the time of registration. # # All auto-registered components are registered in block form. # # When `memoize` is true, the component will be memoized upon first resolution and the same # object returned on all subsequent resolutions, meaning the block is only called once. # Otherwise, the block will be called and a new object returned on every resolution. # # @param key [String] the component's key # @param memoize [Boolean] # @yieldreturn [Object] the object to register as the component # # @overload register(key, call: true, &block) # Registers the given block as the component. When `call: false` is given, then the block # itself will become the component. # # When such a component is resolved, the block will not be called, and instead the `Proc` # object for that block will be returned. # # @param key [String] the component's key # @param call [Boolean] # # @return [container] # # @see #[] # @see #resolve # # @api public # @since 2.0.0 def register(...) container.register(...) end # @overload register_provider(name, namespace: nil, from: nil, source: nil, if: true, &block) # Registers a provider and its lifecycle hooks. # # In most cases, you should call this from a dedicated file for the provider in your app or # slice's `config/providers/` dir. This allows the provider to be loaded when individual # matching components are resolved (for prepared slices) or when slices are booted. # # @example Simple provider # # config/providers/db.rb # Hanami.app.register_provider(:db) do # start do # require "db" # register("db", DB.new) # end # end # # @example Provider with lifecycle steps, also using dependencies from the target container # # config/providers/db.rb # Hanami.app.register_provider(:db) do # prepare do # require "db" # db = DB.new(target_container["settings"].database_url) # register("db", db) # end # # start do # container["db"].establish_connection # end # # stop do # container["db"].close_connection # end # end # # @example Probvider registration under a namespace # # config/providers/db.rb # Hanami.app.register_provider(:persistence, namespace: true) do # start do # require "db" # # # Namespace option above means this will be registered as "persistence.db" # register("db", DB.new) # end # end # # @param name [Symbol] the unique name for the provider # @param namespace [Boolean, String, nil] register components from the provider with given # namespace. May be an explicit string, or `true` for the namespace to be the provider's # name # @param from [Symbol, nil] the group for an external provider source to use, with the # provider source name inferred from `name` or passed explicitly as `source:` # @param source [Symbol, nil] the name of the external provider source to use, if different # from the value provided as `name` # @param if [Boolean] a boolean-returning expression to determine whether to register the # provider # # @return [container] # # @api public # @since 2.0.0 def register_provider(...) container.register_provider(...) end # @api public # @since 2.1.0 def configure_provider(*args, **kwargs, &block) container.register_provider(*args, **kwargs, from: :hanami, &block) end # @overload start(provider_name) # Starts a provider. # # This triggers the provider's `prepare` and `start` lifecycle steps. # # @example # MySlice::Slice.start(:persistence) # # @param provider_name [Symbol] the name of the provider to start # # @return [container] # # @api public # @since 2.0.0 def start(...) container.start(...) end # @overload stop(provider_name) # Stops a provider. # # This triggers the provider's `stop` lifecycle hook. # # @example # MySlice::Slice.stop(:persistence) # # @param provider_name [Symbol] the name of the provider to start # # @return [container] # # @api public # @since 2.0.0 def stop(...) container.stop(...) end # @overload key?(key) # Returns true if the component with the given key is registered in the container. # # For a prepared slice, calling `key?` will also try to load the component if not loaded # already. # # @param key [String, Symbol] the component key # # @return [Boolean] # # @api public # @since 2.0.0 def key?(...) container.key?(...) end # Required for the slice to act as a provider target # @api public # @since 2.2.0 def registered?(...) container.registered?(...) end # Returns an array of keys for all currently registered components in the container. # # For a prepared slice, this will be the set of components that have been previously resolved. # For a booted slice, this will be all components available for the slice. # # @return [Array<String>] # # @api public # @since 2.0.0 def keys container.keys end # @overload [](key) # Resolves the component with the given key from the container. # # For a prepared slice, this will attempt to load and register the matching component if it # is not loaded already. For a booted slice, this will return from already registered # components only. # # @return [Object] the resolved component's object # # @raise Dry::Container::KeyError if the component could not be found or loaded # # @see #resolve # # @api public # @since 2.0.0 def [](...) container.[](...) end # @see #[] # # @api public # @since 2.0.0 def resolve(...) container.resolve(...) end # Specifies the components to export from the slice. # # Slices importing from this slice can import the specified components only. # # @example # module MySlice # class Slice < Hanami::Slice # export ["search", "index_entity"] # end # end # # @param keys [Array<String>] the component keys to export # # @return [self] # # @api public # @since 2.0.0 def export(keys) container.config.exports = keys self end # @overload import(from:, as: nil, keys: nil) # Specifies components to import from another slice. # # Booting a slice will register all imported components. For a prepared slice, these # components will be be imported automatically when resolved. # # @example # module MySlice # class Slice < Hanami:Slice # # Component from Search::Slice will import as "search.index_entity" # import keys: ["index_entity"], from: :search # end # end # # @example Other import variations # # Different key namespace: component will be "search_backend.index_entity" # import keys: ["index_entity"], from: :search, as: "search_backend" # # # Import to root key namespace: component will be "index_entity" # import keys: ["index_entity"], from: :search, as: nil # # # Import all components # import from: :search # # @param keys [Array<String>, nil] Array of component keys to import. To import all # available components, omit this argument. # @param from [Symbol] name of the slice to import from # @param as [Symbol, String, nil] # # @see #export # # @api public # @since 2.0.0 def import(from:, **kwargs) slice = self container.after(:configure) do if from.is_a?(Symbol) || from.is_a?(String) slice_name = from from = slice.parent.slices[from.to_sym].container end as = kwargs[:as] || slice_name import(from: from, as: as, **kwargs) end end # Returns the slice's settings, or nil if no settings are defined. # # You can define your settings in `config/settings.rb`. # # @return [Hanami::Settings, nil] # # @see Hanami::Settings # # @api public # @since 2.0.0 def settings return @settings if instance_variable_defined?(:@settings) @settings = Settings.load_for_slice(self) end # Returns the slice's routes, or nil if no routes are defined. # # You can define your routes in `config/routes.rb`. # # @return [Hanami::Routes, nil] # # @see Hanami::Routes # # @api public # @since 2.0.0 def routes return @routes if instance_variable_defined?(:@routes) @routes = load_routes end # Returns the slice's router, if or nil if no routes are defined. # # An optional `inspector`, implementing the `Hanami::Router::Inspector` interface, may be # provided at first call (the router is then memoized for subsequent accesses). An inspector # is used by the `hanami routes` CLI comment to provide a list of available routes. # # The returned router is a {Slice::Router}, which provides all `Hanami::Router` functionality, # with the addition of support for slice mounting with the {Slice::Router#slice}. # # @param inspector [Hanami::Router::Inspector, nil] an optional routes inspector # # @return [Hanami::Slice::Router, nil] # # @api public # @since 2.0.0 def router(inspector: nil) raise SliceLoadError, "#{self} must be prepared before loading the router" unless prepared? @_mutex.synchronize do @_router ||= load_router(inspector: inspector) end end # Returns a [Rack][rack] app for the slice, or nil if no routes are defined. # # The rack app will be memoized on first access. # # [rack]: https://github.com/rack/rack # # @return [#call, nil] the rack app, or nil if no routes are defined # # @see #routes # @see #router # # @api public # @since 2.0.0 def rack_app return unless router @rack_app ||= router.to_rack_app end # @overload call(rack_env) # Calls the slice's [Rack][rack] app and returns a Rack-compatible response object # # [rack]: https://github.com/rack/rack # # @param rack_env [Hash] the Rack environment for the request # # @return [Array] the three-element Rack response array # # @see #rack_app # # @api public # @since 2.0.0 def call(...) rack_app.call(...) end private # rubocop:disable Metrics/AbcSize def prepare_slice return self if prepared? config.finalize! ensure_slice_name ensure_slice_consts ensure_root prepare_all instance_exec(container, &@prepare_container_block) if @prepare_container_block container.configured! prepare_autoloader # Load child slices last, ensuring their parent is fully prepared beforehand # (useful e.g. for slices that may wish to access constants defined in the # parent's autoloaded directories) prepare_slices @prepared = true self end def ensure_slice_name unless name raise SliceLoadError, "Slice must have a class name before it can be prepared" end end def ensure_slice_consts if namespace.const_defined?(:Container) || namespace.const_defined?(:Deps) raise( SliceLoadError, "#{namespace}::Container and #{namespace}::Deps constants must not already be defined" ) end end def ensure_root unless config.root raise SliceLoadError, "Slice must have a `config.root` before it can be prepared" end end def prepare_all prepare_settings prepare_container_consts prepare_container_plugins prepare_container_base_config prepare_container_component_dirs prepare_container_imports prepare_container_providers end def prepare_settings container.register(:settings, settings) if settings end def prepare_container_consts namespace.const_set :Container, container namespace.const_set :Deps, container.injector end def prepare_container_plugins container.use(:env, inferrer: -> { Hanami.env }) container.use( :zeitwerk, loader: autoloader, run_setup: false, eager_load: false ) end def prepare_container_base_config container.config.name = slice_name.to_sym container.config.root = root container.config.provider_registrar = ProviderRegistrar.for_slice(self) container.config.provider_dirs = [File.join("config", "providers")] container.config.registrations_dir = File.join("config", "registrations") container.config.env = config.env container.config.inflector = config.inflector end def prepare_container_component_dirs return unless root.directory? # Component files in both the root and `lib/` define classes in the slice's # namespace if root.join(LIB_DIR)&.directory? container.config.component_dirs.add(LIB_DIR) do |dir| dir.namespaces.add_root(key: nil, const: slice_name.name) end end # When auto-registering components in the root, ignore files in `config/` (this is # for framework config only), `lib/` (these will be auto-registered as above), as # well as the configured no_auto_register_paths no_auto_register_paths = ([LIB_DIR, CONFIG_DIR] + config.no_auto_register_paths) .map { |path| path.end_with?(File::SEPARATOR) ? path : "#{path}#{File::SEPARATOR}" } # TODO: Change `""` (signifying the root) once dry-rb/dry-system#238 is resolved container.config.component_dirs.add("") do |dir| dir.namespaces.add_root(key: nil, const: slice_name.name) dir.auto_register = -> component { relative_path = component.file_path.relative_path_from(root).to_s !relative_path.start_with?(*no_auto_register_paths) } end end def prepare_container_imports import( keys: config.shared_app_component_keys, from: app.container, as: nil ) end def prepare_container_providers # Check here for the `routes` definition only, not `router` itself, because the # `router` requires the slice to be prepared before it can be loaded, and at this # point we're still in the process of preparing. if routes? require_relative "providers/routes" register_provider(:routes, source: Providers::Routes) end if assets_dir? && Hanami.bundled?("hanami-assets") require_relative "providers/assets" register_provider(:assets, source: Providers::Assets) end if Hanami.bundled?("hanami-db") # Explicit require here to ensure the provider source registers itself, to allow the user # to configure it within their own concrete provider file. require_relative "providers/db" if register_db_provider? # Only register providers if the user hasn't provided their own if !container.providers[:db] register_provider(:db, namespace: true, source: Providers::DB) end if !container.providers[:relations] register_provider(:relations, namespace: true, source: Providers::Relations) end end end end def prepare_autoloader autoloader.tag = "hanami.slices.#{slice_name.to_s}" # Component dirs are automatically pushed to the autoloader by dry-system's zeitwerk plugin. # This method adds other dirs that are not otherwise configured as component dirs. # Everything in the slice root can be autoloaded except `config/` and `slices/`, # which are framework-managed directories if root.join(CONFIG_DIR)&.directory? autoloader.ignore(root.join(CONFIG_DIR)) end if root.join(SLICES_DIR)&.directory? autoloader.ignore(root.join(SLICES_DIR)) end autoloader.setup end def prepare_slices slices.load_slices.each(&:prepare) slices.freeze end def routes? return false unless Hanami.bundled?("hanami-router") return true if namespace.const_defined?(ROUTES_CLASS_NAME) root.join("#{ROUTES_PATH}#{RB_EXT}").file? end def load_routes return false unless Hanami.bundled?("hanami-router") if root.directory? routes_require_path = root.join(ROUTES_PATH).to_s begin require_relative "./routes" require routes_require_path rescue LoadError => e raise e unless e.path == routes_require_path end end begin routes_class = namespace.const_get(ROUTES_CLASS_NAME) routes_class.routes rescue NameError => e raise e unless e.name == ROUTES_CLASS_NAME.to_sym end end def load_router(inspector:) return unless routes require_relative "slice/router" slice = self config = self.config rack_monitor = self["rack.monitor"] show_welcome = Hanami.env?(:development) && routes.empty? render_errors = render_errors? render_detailed_errors = render_detailed_errors? error_handlers = {}.tap do |hsh| if render_errors || render_detailed_errors hsh[:not_allowed] = ROUTER_NOT_ALLOWED_HANDLER hsh[:not_found] = ROUTER_NOT_FOUND_HANDLER end end Slice::Router.new( inspector: inspector, inflector: inflector,
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
true
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/port.rb
lib/hanami/port.rb
# frozen_string_literal: true module Hanami # @since 2.0.1 # @api private module Port # @since 2.0.1 # @api private DEFAULT = 2300 # @since 2.0.1 # @api private ENV_VAR = "HANAMI_PORT" # @since 2.0.1 # @api private def self.call(value, env = ENV.fetch(ENV_VAR, nil)) return Integer(value) if !value.nil? && !default?(value) return Integer(env) unless env.nil? return Integer(value) unless value.nil? DEFAULT end # @since 2.0.1 # @api private def self.call!(value) return if default?(value) ENV[ENV_VAR] = value.to_s end # @since 2.0.1 # @api private def self.default?(value) value.to_i == DEFAULT end class << self # @since 2.0.1 # @api private alias_method :[], :call end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice_name.rb
lib/hanami/slice_name.rb
# frozen_string_literal: true require_relative "constants" module Hanami # Represents the name of an {App} or {Slice}. # # @see Slice::ClassMethods#slice_name # @see App::ClassMethods#app_name # # @api public # @since 2.0.0 class SliceName # Returns a new SliceName for the slice or app. # # You must provide an inflector for the manipulation of the name into various formats. # This should be given in the form of a Proc that returns the inflector when called. # The reason for this is that the inflector may be replaced by the user during the # app configuration phase, so the proc should ensure that the current instance # of the inflector is returned whenever needed. # # @param slice [#name] the slice or app object # @param inflector [Proc] Proc returning the app's inflector when called # # @api private def initialize(slice, inflector:) @slice = slice @inflector = inflector end # Returns the name of the slice as a downcased, underscored string. # # This is considered the canonical name of the slice. # # @example # slice_name.name # => "main" # # @return [String] the slice name # # @api public # @since 2.0.0 def name inflector.underscore(namespace_name) end # @api public # @since 2.0.0 alias_method :path, :name # Returns the name of the slice's module namespace. # # @example # slice_name.namespace_name # => "Main" # # @return [String] the namespace name # # @api public # @since 2.0.0 def namespace_name slice_name.split(MODULE_DELIMITER)[0..-2].join(MODULE_DELIMITER) end # Returns the constant for the slice's module namespace. # # @example # slice_name.namespace_const # => Main # # @return [Module] the namespace module constant # # @api public # @since 2.0.0 def namespace_const inflector.constantize(namespace_name) end # @api public # @since 2.0.0 alias_method :namespace, :namespace_const # @api public # @since 2.0.0 alias_method :to_s, :name # Returns the name of a slice as a downcased, underscored symbol. # # @example # slice_name.name # => :main # # @return [Symbol] the slice name # # @see name, to_s # # @api public # @since 2.0.0 def to_sym name.to_sym end private def slice_name @slice.name end # The inflector is callable to allow for it to be configured/replaced after this # object has been initialized def inflector @inflector.() end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/version.rb
lib/hanami/version.rb
# frozen_string_literal: true module Hanami # Hanami version # # @since 0.9.0 # @api private module Version # @api public VERSION = "2.3.2" # @since 0.9.0 # @api private def self.version VERSION end # @since 0.9.0 # @api private def self.gem_requirement if prerelease? version else "~> #{major_minor}" end end # @since 0.9.0 # @api private def self.prerelease? version =~ /alpha|beta|rc/ end # @since 0.9.0 # @api private def self.major_minor version.scan(/\A\d{1,2}\.\d{1,2}/).first end end # Defines the full version # # @since 0.1.0 VERSION = Version.version end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions.rb
lib/hanami/extensions.rb
# frozen_string_literal: true if Hanami.bundled?("hanami-db") require_relative "extensions/db/repo" end if Hanami.bundled?("hanami-controller") require_relative "extensions/action" end if Hanami.bundled?("hanami-view") require "hanami/view" require_relative "extensions/view" require_relative "extensions/view/context" require_relative "extensions/view/part" require_relative "extensions/view/scope" end if Hanami.bundled?("hanami-router") require_relative "extensions/router/errors" end if Hanami.bundled?("dry-operation") require_relative "extensions/operation" end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/setup.rb
lib/hanami/setup.rb
# frozen_string_literal: true require "bundler/setup" require "hanami" Hanami.setup
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/errors.rb
lib/hanami/errors.rb
# frozen_string_literal: true module Hanami # Base class for all Hanami errors. # # @api public # @since 2.0.0 Error = Class.new(StandardError) # Error raised when {Hanami::App} fails to load. # # @api public # @since 2.0.0 AppLoadError = Class.new(Error) # Error raised when an {Hanami::Slice} fails to load. # # @api public # @since 2.0.0 SliceLoadError = Class.new(Error) # Error raised when an individual component fails to load. # # @api public # @since 2.0.0 ComponentLoadError = Class.new(Error) # Error raised when unsupported middleware configuration is given. # # @see Hanami::Slice::Routing::Middleware::Stack#use # # @api public # @since 2.0.0 UnsupportedMiddlewareSpecError = Class.new(Error) end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/routes.rb
lib/hanami/routes.rb
# frozen_string_literal: true require_relative "constants" require_relative "errors" require_relative "slice/router" module Hanami # App routes # # Users are expected to inherit from this class to define their app # routes. # # @example # # config/routes.rb # # frozen_string_literal: true # # require "hanami/routes" # # module MyApp # class Routes < Hanami::Routes # root to: "home.show" # end # end # # See {Hanami::Slice::Router} for the syntax allowed within the `define` block. # # @see Hanami::Slice::Router # @since 2.0.0 class Routes # Error raised when no action could be found in an app or slice container for the key given in a # routes file. # # @api public # @since 2.0.0 class MissingActionError < Hanami::Error # @api private def initialize(action_key, slice) action_path = action_key.gsub(CONTAINER_KEY_DELIMITER, PATH_DELIMITER) action_constant = slice.inflector.camelize( slice.inflector.underscore(slice.namespace.to_s) + PATH_DELIMITER + action_path ) action_file_path = slice.relative_source_path.join(action_path).to_s.concat(RB_EXT) super(<<~MSG) Could not find action with key #{action_key.inspect} in #{slice} To fix this, define the action class #{action_constant} in #{action_file_path} MSG end end # Error raised when a given routes endpoint does not implement the `#call` interface required # for Rack. # # @api public # @since 2.0.0 class NotCallableEndpointError < Hanami::Error # @api private def initialize(endpoint) super("#{endpoint.inspect} is not compatible with Rack. Please make sure it implements #call.") end end # Wrapper class for the (otherwise opaque) proc returned from {.routes}, adding an `#empty?` # method that returns true if no routes were defined. # # This is useful when needing to determine behaviour based on the presence of user-defined # routes, such as determining whether to show the Hanami welcome page in {Slice#load_router}. # # @api private # @since 2.1.0 class RoutesProc < DelegateClass(Proc) # @api private # @since 2.1.0 def self.empty new(proc {}, empty: true) end # @api private # @since 2.1.0 def initialize(proc, empty: false) @empty = empty super(proc) end # @api private # @since 2.1.0 def empty? !!@empty end end # @api private def self.routes @routes ||= build_routes end class << self # @api private def build_routes(definitions = self.definitions) return RoutesProc.empty if definitions.empty? routes_proc = proc do definitions.each do |(name, args, kwargs, block)| if block public_send(name, *args, **kwargs, &block) else public_send(name, *args, **kwargs) end end end RoutesProc.new(routes_proc) end # @api private def definitions @definitions ||= [] end private # @api private def supported_methods @supported_methods ||= Slice::Router.public_instance_methods end # @api private def respond_to_missing?(name, include_private = false) supported_methods.include?(name) || super end # Capture all method calls that are supported by the router DSL # so that it can be evaluated lazily during configuration/boot # process # # @api private def method_missing(name, *args, **kwargs, &block) return super unless respond_to?(name) definitions << [name, args, kwargs, block] self end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/constants.rb
lib/hanami/constants.rb
# frozen_string_literal: true module Hanami # @api private CONTAINER_KEY_DELIMITER = "." private_constant :CONTAINER_KEY_DELIMITER # @api private MODULE_DELIMITER = "::" private_constant :MODULE_DELIMITER # @api private PATH_DELIMITER = "/" private_constant :PATH_DELIMITER # @api private APP_PATH = "config/app.rb" private_constant :APP_PATH # @api private CONFIG_DIR = "config" private_constant :CONFIG_DIR # @api private APP_DIR = "app" private_constant :APP_DIR # @api private LIB_DIR = "lib" private_constant :LIB_DIR # @api private SLICES_DIR = "slices" private_constant :SLICES_DIR # @api private ROUTES_PATH = File.join(CONFIG_DIR, "routes") private_constant :ROUTES_PATH # @api private ROUTES_CLASS_NAME = "Routes" private_constant :ROUTES_CLASS_NAME # @api private SETTINGS_PATH = File.join(CONFIG_DIR, "settings") private_constant :SETTINGS_PATH # @api private SETTINGS_CLASS_NAME = "Settings" private_constant :SETTINGS_CLASS_NAME # @api private RB_EXT = ".rb" private_constant :RB_EXT # @api private RB_EXT_REGEXP = %r{.rb$} private_constant :RB_EXT_REGEXP # @api private CONTENT_SECURITY_POLICY_NONCE_REQUEST_KEY = "hanami.content_security_policy_nonce" end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/env.rb
lib/hanami/env.rb
# frozen_string_literal: true module Hanami module Env # @since 2.0.1 # @api private @_loaded = false # Uses [dotenv](https://github.com/bkeepers/dotenv) (if available) to populate `ENV` from # various `.env` files. # # For a given `HANAMI_ENV` environment, the `.env` files are looked up in the following order: # # - .env.{environment}.local # - .env.local (unless the environment is `test`) # - .env.{environment} # - .env # # If dotenv is unavailable, the method exits and does nothing. # # @since 2.0.1 # @api private def self.load(env = Hanami.env) return unless Hanami.bundled?("dotenv") return if loaded? dotenv_files = [ ".env.#{env}.local", (".env.local" unless env == :test), ".env.#{env}", ".env" ].compact require "dotenv" Dotenv.load(*dotenv_files) loaded! end # @since 2.0.1 # @api private def self.loaded? @_loaded end # @since 2.0.1 # @api private def self.loaded! @_loaded = true end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/prepare.rb
lib/hanami/prepare.rb
# frozen_string_literal: true require_relative "setup" Hanami.prepare
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/app.rb
lib/hanami/app.rb
# frozen_string_literal: true require_relative "constants" require_relative "env" module Hanami # The Hanami app is a singular slice tasked with managing the core components of the app and # coordinating overall app boot. # # For smaller apps, the app may be the only slice present, whereas larger apps may consist of many # slices, with the app reserved for holding a small number of shared components only. # # @see Slice # # @api public # @since 2.0.0 class App < Slice @_mutex = Mutex.new # @api private # @since 2.0.0 def self.inherited(subclass) super Hanami.app = subclass subclass.extend(ClassMethods) @_mutex.synchronize do subclass.class_eval do @config = Hanami::Config.new(app_name: slice_name, env: Hanami.env) Hanami::Env.load end end end # App class interface module ClassMethods # Returns the app's config. # # @return [Hanami::Config] # # @api public # @since 2.0.0 attr_reader :config # Returns the app's {SliceName}. # # @return [Hanami::SliceName] # # @see Slice::ClassMethods#slice_name # # @api public # @since 2.0.0 def app_name slice_name end # Prepares the $LOAD_PATH based on the app's configured root, prepending the `lib/` directory # if it exists. If the lib directory is already added, this will do nothing. # # In ordinary circumstances, you should never have to call this method: this method is called # immediately upon subclassing {Hanami::App}, as a convenicence to put lib/ (under the default # root of `Dir.pwd`) on the load path automatically. This is helpful if you need to require # files inside the subclass body for performing certain app configuration steps. # # If you change your app's `config.root` and you need to require files from its `lib/` # directory within your {App} subclass body, you should call {.prepare_load_path} explicitly # after setting the new root. # # Otherwise, this method is called again as part of the app {.prepare} step, so if you've # changed your app's root and do _not_ need to require files within your {App} subclass body, # then you don't need to call this method. # # @example # module MyApp # class App < Hanami::App # config.root = Pathname(__dir__).join("../src") # prepare_load_path # # # You can make requires for your files here # end # end # # @return [self] # # @api public # @since 2.0.0 def prepare_load_path if (lib_path = root.join(LIB_DIR)).directory? path = lib_path.realpath.to_s $LOAD_PATH.prepend(path) unless $LOAD_PATH.include?(path) end self end private def prepare_all prepare_load_path # Make app-wide notifications available as early as possible container.use(:notifications) # Ensure all basic slice preparation is complete before we make adjustments below (which # rely on the basic prepare steps having already run) super # Run specific prepare steps for the app slice. Note also that some standard steps have been # skipped via the empty method overrides below. prepare_app_component_dirs prepare_app_providers end # Skip standard slice prepare steps that do not apply to the app def prepare_container_component_dirs; end def prepare_container_imports; end # rubocop:disable Metrics/AbcSize def prepare_app_component_dirs # Component files in both `app/` and `app/lib/` define classes in the # app's namespace if root.join(APP_DIR, LIB_DIR).directory? container.config.component_dirs.add(File.join(APP_DIR, LIB_DIR)) do |dir| dir.namespaces.add_root(key: nil, const: app_name.name) end end # When auto-registering components in `app/`, ignore files in `app/lib/` (these will be # auto-registered as above), as well as the configured no_auto_register_paths no_auto_register_paths = ([LIB_DIR] + config.no_auto_register_paths) .map { |path| path.end_with?(File::SEPARATOR) ? path : "#{path}#{File::SEPARATOR}" } if root.join(APP_DIR).directory? container.config.component_dirs.add(APP_DIR) do |dir| dir.namespaces.add_root(key: nil, const: app_name.name) dir.auto_register = -> component { relative_path = component.file_path.relative_path_from(root.join(APP_DIR)).to_s !relative_path.start_with?(*no_auto_register_paths) } end end end def prepare_app_providers require_relative "providers/inflector" register_provider(:inflector, source: Hanami::Providers::Inflector) # Allow logger to be replaced by users with a manual provider, for advanced cases unless container.providers[:logger] require_relative "providers/logger" register_provider(:logger, source: Hanami::Providers::Logger) end if Hanami.bundled?("rack") require_relative "providers/rack" register_provider(:rack, source: Hanami::Providers::Rack, namespace: true) end if Hanami.bundled?("hanami-db") register_provider(:db_logging, source: Hanami::Providers::DBLogging) end end def prepare_autoloader autoloader.tag = "hanami.app.#{slice_name.name}" # Component dirs are automatically pushed to the autoloader by dry-system's zeitwerk plugin. # This method adds other dirs that are not otherwise configured as component dirs. # Autoload classes from `lib/[app_namespace]/` if root.join(LIB_DIR, app_name.name).directory? autoloader.push_dir(root.join(LIB_DIR, app_name.name), namespace: namespace) end autoloader.setup end # rubocop:enable Metrics/AbcSize end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/settings.rb
lib/hanami/settings.rb
# frozen_string_literal: true require "dry/core/constants" require "dry/configurable" require_relative "errors" module Hanami # Provides user-defined settings for an Hanami app or slice. # # Define your own settings by inheriting from this class in `config/settings.rb` within an app or # slice. Your settings will be loaded from matching ENV vars (with upper-cased names) and be # registered as a component as part of the Hanami app {Hanami::Slice::ClassMethods#prepare # prepare} step. # # The settings instance is registered in your app and slice containers as a `"settings"` # component. You can use the `Deps` mixin to inject this dependency and make settings available to # your other components as required. # # @example # # config/settings.rb # # frozen_string_literal: true # # module MyApp # class Settings < Hanami::Settings # Secret = Types::String.constrained(min_size: 20) # # setting :database_url, constructor: Types::String # setting :session_secret, constructor: Secret # setting :some_flag, default: false, constructor: Types::Params::Bool # end # end # # Settings are defined with [dry-configurable][dry-c]'s `setting` method. You may likely want to # provide `default:` and `constructor:` options for your settings. # # If you have [dry-types][dry-t] bundled, then a nested `Types` module will be available for type # checking your setting values. Pass type objects to the setting `constructor:` options to ensure # their values meet your type expectations. You can use dry-types' default type objects or define # your own. # # When the settings are initialized, all type errors will be collected and presented together for # correction. Settings are loaded early, as part of the Hanami app's # {Hanami::Slice::ClassMethods#prepare prepare} step, to ensure that the app boots only when valid # settings are present. # # Setting values are loaded from a configurable store, which defaults to # {Hanami::Settings::EnvStore}, which fetches the values from equivalent upper-cased keys in # `ENV`. You can configure an alternative store via {Hanami::Config#settings_store}. Setting stores # must implement a `#fetch` method with the same signature as `Hash#fetch`. # # [dry-c]: https://dry-rb.org/gems/dry-configurable/ # [dry-t]: https://dry-rb.org/gems/dry-types/ # # @see Hanami::Settings::DotenvStore # # @api public # @since 2.0.0 class Settings # Error raised when setting values do not meet their type expectations. # # Its message collects all the individual errors that can be raised for each setting. # # @api public # @since 2.0.0 class InvalidSettingsError < Hanami::Error # @api private def initialize(errors) super() @errors = errors end # Returns the exception's message. # # @return [String] # # @api public # @since 2.0.0 def to_s <<~STR.strip Could not initialize settings. The following settings were invalid: #{@errors.map { |setting, message| "#{setting}: #{message}" }.join("\n")} STR end end class << self # Defines a nested `Types` constant in `Settings` subclasses if dry-types is bundled. # # @see https://dry-rb.org/gems/dry-types # # @api private def inherited(subclass) super if Hanami.bundled?("dry-types") require "dry/types" subclass.const_set(:Types, Dry.Types()) end end # Loads the settings for a slice. # # Returns nil if no settings class is defined. # # @return [Settings, nil] # # @api private def load_for_slice(slice) return unless settings_defined?(slice) require_slice_settings(slice) unless slice_settings_class?(slice) slice_settings_class(slice).new(slice.config.settings_store) end private # Returns true if settings are defined for the slice. # # Settings are considered defined if a `Settings` class is already defined in the slice # namespace, or a `config/settings.rb` exists under the slice root. def settings_defined?(slice) slice.namespace.const_defined?(SETTINGS_CLASS_NAME) || slice.root.join("#{SETTINGS_PATH}#{RB_EXT}").file? end def slice_settings_class?(slice) slice.namespace.const_defined?(SETTINGS_CLASS_NAME) end def slice_settings_class(slice) slice.namespace.const_get(SETTINGS_CLASS_NAME) end def require_slice_settings(slice) require "hanami/settings" slice_settings_require_path = File.join(slice.root, SETTINGS_PATH) begin require slice_settings_require_path rescue LoadError => e raise e unless e.path == slice_settings_require_path end end end # @api private Undefined = Dry::Core::Constants::Undefined # @api private EMPTY_STORE = Dry::Core::Constants::EMPTY_HASH include Dry::Configurable # @api private def initialize(store = EMPTY_STORE) errors = config._settings.map(&:name).each_with_object({}) do |name, errs| value = store.fetch(name, Undefined) if value.eql?(Undefined) # When a key is missing entirely from the store, _read_ its value from the config instead. # This ensures its setting constructor runs (with a `nil` argument given) and raises any # necessary errors. public_send(name) else public_send("#{name}=", value) end rescue => e # rubocop:disable Style/RescueStandardError errs[name] = e end raise InvalidSettingsError, errors if errors.any? config.finalize! end # Returns a string containing a human-readable representation of the settings. # # This includes setting names only, not any values, to ensure that sensitive values do not # inadvertently leak. # # Use {#inspect_values} to inspect settings with their values. # # @example # settings.inspect # # => #<MyApp::Settings [database_url, session_secret, some_flag]> # # @return [String] # # @see #inspect_values # # @api public # @since 2.0.0 def inspect "#<#{self.class} [#{config._settings.map(&:name).join(", ")}]>" end # rubocop:disable Layout/LineLength # Returns a string containing a human-readable representation of the settings and their values. # # @example # settings.inspect_values # # => #<MyApp::Settings database_url="postgres://localhost/my_db", session_secret="xxx", some_flag=true]> # # @return [String] # # @see #inspect # # @api public # @since 2.0.0 def inspect_values "#<#{self.class} #{config._settings.map { |setting| "#{setting.name}=#{config[setting.name].inspect}" }.join(" ")}>" end # rubocop:enable Layout/LineLength private def method_missing(name, *args, &block) if config.respond_to?(name) config.send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || super end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/provider_registrar.rb
lib/hanami/provider_registrar.rb
# frozen_string_literal: true # @api private # @since 2.2.0 module Hanami class ProviderRegistrar < Dry::System::ProviderRegistrar def self.for_slice(slice) Class.new(self) do define_singleton_method(:new) do |container| super(container, slice) end end end attr_reader :slice def initialize(container, slice) super(container) @slice = slice end def provider_source_class = Hanami::Provider::Source def provider_source_options {slice: slice} end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice_configurable.rb
lib/hanami/slice_configurable.rb
# frozen_string_literal: true require_relative "constants" require_relative "errors" module Hanami # Calls `configure_for_slice(slice)` on the extended class whenever it is first # subclassed within a module namespace corresponding to a slice. # # @example # class BaseClass # extend Hanami::SliceConfigurable # end # # # slices/main/lib/my_class.rb # module Main # class MyClass < BaseClass # # Will be called with `Main::Slice` # def self.configure_for_slice(slice) # # ... # end # end # end # # @api private # @since 2.0.0 module SliceConfigurable class << self def extended(klass) slice_for = method(:slice_for) inherited_mod = Module.new do define_method(:inherited) do |subclass| unless Hanami.app? raise ComponentLoadError, "Class #{klass} must be defined within an Hanami app" end super(subclass) subclass.instance_variable_set(:@configured_for_slices, configured_for_slices.dup) slice = slice_for.(subclass) return unless slice unless subclass.configured_for_slice?(slice) subclass.configure_for_slice(slice) if subclass.respond_to?(:configure_for_slice) subclass.configured_for_slices << slice end end end klass.singleton_class.prepend(inherited_mod) end private def slice_for(klass) return unless klass.name slices = Hanami.app.slices.with_nested + [Hanami.app] slices.detect { |slice| klass.name.start_with?("#{slice.namespace}#{MODULE_DELIMITER}") } end end def configured_for_slice?(slice) configured_for_slices.include?(slice) end def configured_for_slices @configured_for_slices ||= [] end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config.rb
lib/hanami/config.rb
# frozen_string_literal: true require "uri" require "pathname" require "dry/configurable" require "dry/inflector" require_relative "constants" require_relative "config/console" module Hanami # Hanami app config # # @since 2.0.0 class Config include Dry::Configurable # @!attribute [rw] root # Sets the root for the app or slice. # # For the app, this defaults to `Dir.pwd`. For slices detected in `slices/` `config/slices/`, # this defaults to `slices/[slice_name]/`. # # Accepts a string path and will return a `Pathname`. # # @return [Pathname] # # @api public # @since 2.0.0 setting :root, constructor: ->(path) { Pathname(path) if path } # @!attribute [rw] inflector # Sets the app's inflector. # # This expects a `Dry::Inflector` (or compatible) inflector instance. # # To configure custom inflection rules without having to assign a whole inflector, see # {#inflections}. # # @return [Dry::Inflector] # # @see #inflections # # @api public # @since 2.0.0 setting :inflector, default: Dry::Inflector.new # @!attribute [rw] settings_store # Sets the store used to retrieve {Hanami::Settings} values. # # Defaults to an instance of {Hanami::Settings::EnvStore}. # # @return [#fetch] # # @see Hanami::Settings # @see Hanami::Settings::EnvStore#fetch # # @api public # @since 2.0.0 setting :settings_store, default: Hanami::Settings::EnvStore.new # @!attribute [rw] slices # Sets the slices to load when the app is preared or booted. # # Defaults to `nil`, which will load all slices. Set this to an array of slice names to load # only those slices. # # This attribute is also populated from the `HANAMI_SLICES` environment variable. # # @example # config.slices = ["admin", "search"] # # @example # ENV["HANAMI_SLICES"] # => "admin,search" # config.slices # => ["admin", "search"] # # @return [Array<String>, nil] # # @api public # @since 2.0.0 setting :slices # @!attribute [rw] shared_app_component_keys # Sets the keys for the components to be imported from the app into all other slices. # # You should append items to this array, since the default shared components are essential for # slices to operate within the app. # # @example # config.shared_app_component_keys += ["shared_component_a", "shared_component_b"] # # @return [Array<String>] # # @api public # @since 2.0.0 setting :shared_app_component_keys, default: %w[ inflector logger notifications rack.monitor routes settings ] # @!attribute [rw] no_auto_register_paths # Sets the paths to skip from container auto-registration. # # Defaults to `["entities"]`. # # @return [Array<String>] array of relative paths # # @api public # @since 2.0.0 setting :no_auto_register_paths, default: [ "db", "entities", "relations", "structs" ] # @!attribute [rw] base_url # Sets the base URL for app's web server. # # This is passed to the {Slice::ClassMethods#router router} and used for generating links. # # Defaults to `"http://0.0.0.0:2300"`. String values passed are turned into `URI` instances. # # @return [URI] # # @see Slice::ClassMethods#router # # @api public # @since 2.0.0 setting :base_url, default: "http://0.0.0.0:2300", constructor: ->(url) { URI(url) } # @!attribute [rw] render_errors # Sets whether to catch exceptions and render error pages. # # For HTML responses, these error pages are in `public/{404,500}.html`. # # Defaults to `true` in production mode, `false` in all others. # # @return [Boolean] # # @api public # @since 2.1.0 setting :render_errors, default: false # @!attribute [rw] render_detailed_errors # Sets whether to catch exceptions and render detailed, interactive error pages. # # Requires the hanami-webconsole gem to be available. # # Defaults to `false` in production mode, `true` in all others. # # @return [Boolean] # # @api public # @since 2.1.0 setting :render_detailed_errors, default: false # @!attribute [rw] render_error_responses # Sets a mapping of exception class names (as strings) to symbolic response status codes used # for rendering error responses. # # The response status codes will be passed to `Rack::Utils.status_code`. # # In ordinary usage, you should not replace this hash. Instead, add keys and values for the # errors you want handled. # # @example # config.render_error_responses # # => {"Hanami::Router::NotFoundError" => :not_found} # # config.render_error_responses["MyNotFoundError"] = :not_found # # @return [Hash{String => Symbol}] # # @see #render_errors # # @api public # @since 2.1.0 setting :render_error_responses, default: Hash.new(:internal_server_error).merge!( "Hanami::Router::NotAllowedError" => :not_found, "Hanami::Router::NotFoundError" => :not_found, ) # @!attribute [rw] console # Returns the app's console config # # @example # config.console.engine # => :irb # # @return [Hanami::Config::Console] # # @api public # @since 2.3.0 setting :console, default: Hanami::Config::Console.new # Returns the app or slice's {Hanami::SliceName slice_name}. # # This is useful for default config values that depend on this name. # # @return [Hanami::SliceName] # # @api private # @since 2.0.0 attr_reader :app_name # Returns the app's environment. # # @example # config.env # => :development # # @return [Symbol] # # @see #environment # # @api private # @since 2.0.0 attr_reader :env # Returns the app's actions config, or a null config if hanami-controller is not bundled. # # @example When hanami-controller is bundled # config.actions.default_request_format # => :html # # @example When hanami-controller is not bundled # config.actions.default_request_format # => NoMethodError # # @return [Hanami::Config::Actions, Hanami::Config::NullConfig] # # @api public # @since 2.0.0 attr_reader :actions # Returns the app's db config, or a null config if hanami-db is not bundled. # # @example When hanami-db is bundled # config.db.import_from_parent # => false # # @example When hanami-db is not bundle # config.db.import_from_parent # => NoMethodError # # @return [Hanami::Config::DB, Hanami::Config::NullConfig] # # @api public # @since 2.2.0 attr_reader :db # Returns the app's middleware stack, or nil if hanami-router is not bundled. # # Use this to configure middleware that should apply to all routes. # # @example # config.middleware.use :body_parser, :json # config.middleware.use MyCustomMiddleware # # @return [Hanami::Slice::Routing::Middleware::Stack, nil] # # @api public # @since 2.0.0 attr_reader :middleware # @api private # @since 2.0.0 alias_method :middleware_stack, :middleware # Returns the app's router config, or a null config if hanami-router is not bundled. # # @example When hanami-router is bundled # config.router.resolver # => Hanami::Slice::Routing::Resolver # # @example When hanami-router is not bundled # config.router.resolver # => NoMethodError # # @return [Hanami::Config::Router, Hanami::Config::NullConfig] # # @api public # @since 2.0.0 attr_reader :router # Returns the app's views config, or a null config if hanami-view is not bundled. # # @example When hanami-view is bundled # config.views.paths # => [...] # # @example When hanami-view is not bundled # config.views.paths # => NoMethodError # # @return [Hanami::Config::Views, Hanami::Config::NullConfig] # # @api public # @since 2.1.0 attr_reader :views # Returns the app's views config, or a null config if hanami-view is not bundled. # # @example When hanami-view is bundled # config.views.paths # => [...] # # @example When hanami-view is not bundled # config.views.paths # => NoMethodError # # @return [Hanami::Config::Assets, Hanami::Config::NullConfig] # # @api public # @since 2.1.0 attr_reader :assets # @api private # rubocop:disable Metrics/AbcSize def initialize(app_name:, env:) @app_name = app_name @env = env # Apply default values that are only knowable at initialize-time (vs require-time) self.root = Dir.pwd self.render_errors = (env == :production) self.render_detailed_errors = (env == :development) load_from_env @actions = load_dependent_config("hanami-controller") { require_relative "config/actions" Actions.new } @assets = load_dependent_config("hanami-assets") { require_relative "config/assets" Hanami::Config::Assets.new } @db = load_dependent_config("hanami-db") { DB.new } @logger = Config::Logger.new(env: env, app_name: app_name) @middleware = load_dependent_config("hanami-router") { require_relative "slice/routing/middleware/stack" Slice::Routing::Middleware::Stack.new } @router = load_dependent_config("hanami-router") { require_relative "config/router" Router.new(self) } @views = load_dependent_config("hanami-view") { require_relative "config/views" Views.new } yield self if block_given? end # rubocop:enable Metrics/AbcSize # @api private def initialize_copy(source) super @app_name = app_name.dup @actions = source.actions.dup @assets = source.assets.dup @db = source.db.dup @logger = source.logger.dup @middleware = source.middleware.dup @router = source.router.dup.tap do |router| router.instance_variable_set(:@base_config, self) end @views = source.views.dup end private :initialize_copy # Finalizes the config. # # This is called when the app or slice is prepared. After this, no further changes to config can # be made. # # @api private def finalize! # Finalize nested configs assets.finalize! actions.finalize!(self) views.finalize! logger.finalize! router.finalize! use_body_parser_middleware super end # Configures the app's custom inflections. # # You should call this one time only. Subsequent calls will override previously configured # inflections. # # @example # config.inflections do |inflections| # inflections.acronym "WNBA" # end # # @see https://dry-rb.org/gems/dry-inflector # # @return [Dry::Inflector] the configured inflector # # @api public # @since 2.0.0 def inflections(&block) self.inflector = Dry::Inflector.new(&block) end # Disabling this to permit distinct documentation for `#logger` vs `#logger=` # # rubocop:disable Style/TrivialAccessors # Returns the logger config. # # Use this to configure various options for the default `Dry::Logger::Dispatcher` logger instance. # # @example # config.logger.level = :debug # # @return [Hanami::Config::Logger] # # @see Hanami::Config::Logger # # @api public # @since 2.0.0 def logger @logger end # Sets the app's logger instance. # # This entirely replaces the default `Dry::Logger::Dispatcher` instance that would have been # # @see #logger_instance # # @api public # @since 2.0.0 def logger=(logger_instance) @logger_instance = logger_instance end # rubocop:enable Style/TrivialAccessors # Returns the configured logger instance. # # Unless you've replaced the logger with {#logger=}, this returns a `Dry::Logger::Dispatcher` configured # with the options configured through {#logger}. # # This configured logger is registered in all app and slice containers as `"logger"`. For # typical usage, you should access the logger via this component, not directly from config. # # @example Accessing the logger component # Hanami.app["logger"] # => #<Dry::Logger::Dispatcher> # # @example Injecting the logger as a dependency # module MyApp # class MyClass # include Deps["logger"] # # def my_method # logger.info("hello") # end # end # end # # @return [Dry::Logger::Dispatcher] # # @see #logger # @see Hanami::Config::Logger # # @api public # @since 2.0.0 def logger_instance @logger_instance || logger.instance end private def load_from_env self.slices = ENV["HANAMI_SLICES"]&.split(",")&.map(&:strip) end DEFAULT_MIDDLEWARE_PARSERS = { form: ["multipart/form-data"], json: ["application/json", "application/vnd.api+json"] }.freeze private_constant :DEFAULT_MIDDLEWARE_PARSERS def use_body_parser_middleware return unless Hanami.bundled?("hanami-router") && Hanami.bundled?("hanami-controller") middleware.use(:body_parser, [DEFAULT_MIDDLEWARE_PARSERS]) end def load_dependent_config(gem_name) if Hanami.bundled?(gem_name) yield else require_relative "config/null_config" NullConfig.new end end def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || super end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice_registrar.rb
lib/hanami/slice_registrar.rb
# frozen_string_literal: true require_relative "constants" module Hanami # @api private class SliceRegistrar VALID_SLICE_NAME_RE = /^[a-z][a-z0-9_]*$/ SLICE_DELIMITER = CONTAINER_KEY_DELIMITER attr_reader :parent, :slices private :parent, :slices def initialize(parent) @parent = parent @slices = {} end def register(name, slice_class = nil, &block) unless name.to_s =~ VALID_SLICE_NAME_RE raise ArgumentError, "slice name #{name.inspect} must be lowercase alphanumeric text and underscores only" end return unless filter_slice_names([name]).any? if slices.key?(name.to_sym) raise SliceLoadError, "Slice '#{name}' is already registered" end slice = slice_class || build_slice(name, &block) configure_slice(name, slice) slices[name.to_sym] = slice end def [](name) slices.fetch(name) do raise SliceLoadError, "Slice '#{name}' not found" end end def freeze slices.freeze super end def load_slices slice_configs = root.join(CONFIG_DIR, SLICES_DIR).glob("*#{RB_EXT}") .map { _1.basename(RB_EXT) } slice_dirs = root.join(SLICES_DIR).glob("*") .select(&:directory?) .map { _1.basename } (slice_dirs + slice_configs).uniq.sort .then { filter_slice_names(_1) } .each(&method(:load_slice)) self end def each(&block) slices.each_value(&block) end def keys slices.keys end def to_a slices.values end def with_nested to_a.flat_map { |slice| # Return nested slices first so that their more specific namespaces may be picked up first # by SliceConfigurable#slice_for slice.slices.with_nested + [slice] } end private def root parent.root end def inflector parent.inflector end def parent_slice_namespace parent.eql?(parent.app) ? Object : parent.namespace end # Runs when a slice file has been found inside the app at `config/slices/[slice_name].rb`, # or when a slice directory exists at `slices/[slice_name]`. # # If a slice definition file is found by `find_slice_require_path`, then `load_slice` will # require the file before registering the slice class. # # If a slice class is not found, registering the slice will generate the slice class. def load_slice(slice_name) slice_require_path = find_slice_require_path(slice_name) require slice_require_path if slice_require_path slice_class = begin inflector.constantize("#{slice_module_name(slice_name)}#{MODULE_DELIMITER}Slice") rescue NameError => e raise e unless e.name.to_s == inflector.camelize(slice_name) || e.name.to_s == :Slice end register(slice_name, slice_class) end # Finds the path to the slice's definition file, if it exists, in the following order: # # 1. `config/slices/[slice_name].rb` # 2. `slices/[parent_slice_name]/config/[slice_name].rb` (unless parent is the app) # 3. `slices/[slice_name]/config/slice.rb` # # If the slice is nested under another slice then it will look in the following order: # # 1. `config/slices/[parent_slice_name]/[slice_name].rb` # 2. `slices/[parent_slice_name]/config/[slice_name].rb` # 3. `slices/[parent_slice_name]/[slice_name]/config/slice.rb` def find_slice_require_path(slice_name) app_slice_file_path = [slice_name] app_slice_file_path.prepend(parent.slice_name) unless parent.eql?(parent.app) ancestors = [ parent.app.root.join(CONFIG_DIR, SLICES_DIR, app_slice_file_path.join(File::SEPARATOR)), parent.root.join(CONFIG_DIR, SLICES_DIR, slice_name), root.join(SLICES_DIR, slice_name, CONFIG_DIR, "slice") ] ancestors .uniq .find { _1.sub_ext(RB_EXT).file? } &.to_s end def build_slice(slice_name, &block) slice_module = begin inflector.constantize(slice_module_name(slice_name)) rescue NameError parent_slice_namespace.const_set(inflector.camelize(slice_name), Module.new) end slice_module.const_set(:Slice, Class.new(Hanami::Slice, &block)) end def slice_module_name(slice_name) inflector.camelize("#{parent_slice_namespace.name}#{PATH_DELIMITER}#{slice_name}") end def configure_slice(slice_name, slice) slice.instance_variable_set(:@parent, parent) # Slices require a root, so provide a sensible default based on the slice's parent slice.config.root ||= root.join(SLICES_DIR, slice_name.to_s) slice.config.slices = child_slice_names(slice_name, parent.config.slices) end # Returns a filtered array of slice names based on the parent's `config.slices` # # This works with both singular slice names (e.g. `"admin"`) as well as dot-delimited nested # slice names (e.g. `"admin.shop"`). # # It will consider only the base names of the slices (since in this case, a parent slice must be # loaded in order for its children to be loaded). # # @example # parent.config.slices # => ["admin.shop"] # filter_slice_names(["admin", "main"]) # => ["admin"] # # parent.config.slices # => ["admin"] # filter_slice_names(["admin", "main"]) # => ["admin"] def filter_slice_names(slice_names) slice_names = slice_names.map(&:to_s) if parent.config.slices slice_names & parent.config.slices.map { base_slice_name(_1) } else slice_names end end # Returns the base slice name from an (optionally) dot-delimited nested slice name. # # @example # base_slice_name("admin") # => "admin" # base_slice_name("admin.users") # => "admin" def base_slice_name(name) name.to_s.split(SLICE_DELIMITER).first end # Returns an array of slice names specific to the given child slice. # # @example # child_local_slice_names("admin", ["main", "admin.users"]) # => ["users"] def child_slice_names(parent_slice_name, slice_names) slice_names &.select { |name| name.include?(SLICE_DELIMITER) && name.split(SLICE_DELIMITER)[0] == parent_slice_name.to_s } &.map { |name| name.split(SLICE_DELIMITER)[1..].join(SLICE_DELIMITER) # which version of Ruby supports this? } end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/boot.rb
lib/hanami/boot.rb
# frozen_string_literal: true require_relative "setup" Hanami.boot
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/helpers/assets_helper.rb
lib/hanami/helpers/assets_helper.rb
# frozen_string_literal: true require "uri" require "hanami/view" require_relative "../constants" # rubocop:disable Metrics/ModuleLength module Hanami module Helpers # HTML assets helpers # # Inject these helpers in a view # # @since 2.1.0 # # @see http://www.rubydoc.info/gems/hanami-helpers/Hanami/Helpers/HtmlHelper module AssetsHelper # @since 2.1.0 # @api private NEW_LINE_SEPARATOR = "\n" # @since 2.1.0 # @api private WILDCARD_EXT = ".*" # @since 2.1.0 # @api private JAVASCRIPT_EXT = ".js" # @since 2.1.0 # @api private STYLESHEET_EXT = ".css" # @since 2.1.0 # @api private JAVASCRIPT_MIME_TYPE = "text/javascript" # @since 2.1.0 # @api private STYLESHEET_MIME_TYPE = "text/css" # @since 2.1.0 # @api private FAVICON_MIME_TYPE = "image/x-icon" # @since 2.1.0 # @api private STYLESHEET_REL = "stylesheet" # @since 2.1.0 # @api private FAVICON_REL = "shortcut icon" # @since 2.1.0 # @api private DEFAULT_FAVICON = "favicon.ico" # @since 0.3.0 # @api private CROSSORIGIN_ANONYMOUS = "anonymous" # @since 0.3.0 # @api private # TODO: we can drop the defined?-check and fallback once Ruby 3.3 becomes our minimum required version ABSOLUTE_URL_MATCHER = ( defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::DEFAULT_PARSER ).make_regexp # @since 1.1.0 # @api private QUERY_STRING_MATCHER = /\?/ include Hanami::View::Helpers::TagHelper # Generate `script` tag for given source(s) # # It accepts one or more strings representing the name of the asset, if it # comes from the application or third party gems. It also accepts strings # representing absolute URLs in case of public CDN (eg. jQuery CDN). # # If the "fingerprint mode" is on, `src` is the fingerprinted # version of the relative URL. # # If the "CDN mode" is on, the `src` is an absolute URL of the # application CDN. # # If the "subresource integrity mode" is on, `integrity` is the # name of the algorithm, then a hyphen, then the hash value of the file. # If more than one algorithm is used, they"ll be separated by a space. # # If the Content Security Policy uses 'nonce' and the source is not # absolute, the nonce value of the current request is automatically added # as an attribute. You can override this with the `nonce: false` option. # See {#content_security_policy_nonce} for more. # # @param sources [Array<String, #url>] one or more assets by name or absolute URL # # @return [Hanami::View::HTML::SafeString] the markup # # @raise [Hanami::Assets::MissingManifestAssetError] if `fingerprint` or # `subresource_integrity` modes are on and the javascript file is missing # from the manifest # # @since 2.1.0 # # @see Hanami::Assets::Helpers#path # # @example Single Asset # # <%= javascript_tag "application" %> # # # <script src="/assets/application.js" type="text/javascript"></script> # # @example Multiple Assets # # <%= javascript_tag "application", "dashboard" %> # # # <script src="/assets/application.js" type="text/javascript"></script> # # <script src="/assets/dashboard.js" type="text/javascript"></script> # # @example Asynchronous Execution # # <%= javascript_tag "application", async: true %> # # # <script src="/assets/application.js" type="text/javascript" async="async"></script> # # @example Subresource Integrity # # <%= javascript_tag "application" %> # # # <script src="/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.js" # # type="text/javascript" integrity="sha384-oqVu...Y8wC" crossorigin="anonymous"></script> # # @example Subresource Integrity for 3rd Party Scripts # # <%= javascript_tag "https://example.com/assets/example.js", integrity: "sha384-oqVu...Y8wC" %> # # # <script src="https://example.com/assets/example.js" type="text/javascript" # # integrity="sha384-oqVu...Y8wC" crossorigin="anonymous"></script> # # @example Deferred Execution # # <%= javascript_tag "application", defer: true %> # # # <script src="/assets/application.js" type="text/javascript" defer="defer"></script> # # @example Disable nonce # # <%= javascript_tag "application", nonce: false %> # # @example Absolute URL # # <%= javascript_tag "https://code.jquery.com/jquery-2.1.4.min.js" %> # # # <script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script> # # @example Fingerprint Mode # # <%= javascript_tag "application" %> # # # <script src="/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.js" type="text/javascript"></script> # # @example CDN Mode # # <%= javascript_tag "application" %> # # # <script src="https://assets.bookshelf.org/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.js" # # type="text/javascript"></script> def javascript_tag(*sources, **options) options = options.reject { |k, _| k.to_sym == :src } nonce_option = options.delete(:nonce) _safe_tags(*sources) do |source| attributes = { src: _typed_url(source, JAVASCRIPT_EXT), type: JAVASCRIPT_MIME_TYPE, nonce: _nonce(source, nonce_option) } attributes.merge!(options) if _context.assets.subresource_integrity? || attributes.include?(:integrity) attributes[:integrity] ||= _subresource_integrity_value(source, JAVASCRIPT_EXT) attributes[:crossorigin] ||= CROSSORIGIN_ANONYMOUS end tag.script(**attributes).to_s end end # Generate `link` tag for given source(s) # # It accepts one or more strings representing the name of the asset, if it # comes from the application or third party gems. It also accepts strings # representing absolute URLs in case of public CDN (eg. Bootstrap CDN). # # If the "fingerprint mode" is on, `href` is the fingerprinted # version of the relative URL. # # If the "CDN mode" is on, the `href` is an absolute URL of the # application CDN. # # If the "subresource integrity mode" is on, `integrity` is the # name of the algorithm, then a hyphen, then the hashed value of the file. # If more than one algorithm is used, they"ll be separated by a space. # # If the Content Security Policy uses 'nonce' and the source is not # absolute, the nonce value of the current request is automatically added # as an attribute. You can override this with the `nonce: false` option. # See {#content_security_policy_nonce} for more. # # @param sources [Array<String, #url>] one or more assets by name or absolute URL # # @return [Hanami::View::HTML::SafeString] the markup # # @raise [Hanami::Assets::MissingManifestAssetError] if `fingerprint` or # `subresource_integrity` modes are on and the stylesheet file is missing # from the manifest # # @since 2.1.0 # # @see Hanami::Assets::Helpers#path # # @example Single Asset # # <%= stylesheet_tag "application" %> # # # <link href="/assets/application.css" type="text/css" rel="stylesheet"> # # @example Multiple Assets # # <%= stylesheet_tag "application", "dashboard" %> # # # <link href="/assets/application.css" type="text/css" rel="stylesheet"> # # <link href="/assets/dashboard.css" type="text/css" rel="stylesheet"> # # @example Disable nonce # # <%= stylesheet_tag "application", nonce: false %> # # @example Subresource Integrity # # <%= stylesheet_tag "application" %> # # # <link href="/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.css" # # type="text/css" integrity="sha384-oqVu...Y8wC" crossorigin="anonymous"></script> # # @example Subresource Integrity for 3rd Party Assets # # <%= stylesheet_tag "https://example.com/assets/example.css", integrity: "sha384-oqVu...Y8wC" %> # # # <link href="https://example.com/assets/example.css" # # type="text/css" rel="stylesheet" integrity="sha384-oqVu...Y8wC" crossorigin="anonymous"></script> # # @example Absolute URL # # <%= stylesheet_tag "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" %> # # # <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" # # type="text/css" rel="stylesheet"> # # @example Fingerprint Mode # # <%= stylesheet_tag "application" %> # # # <link href="/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.css" type="text/css" rel="stylesheet"> # # @example CDN Mode # # <%= stylesheet_tag "application" %> # # # <link href="https://assets.bookshelf.org/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.css" # # type="text/css" rel="stylesheet"> def stylesheet_tag(*sources, **options) options = options.reject { |k, _| k.to_sym == :href } nonce_option = options.delete(:nonce) _safe_tags(*sources) do |source| attributes = { href: _typed_url(source, STYLESHEET_EXT), type: STYLESHEET_MIME_TYPE, rel: STYLESHEET_REL, nonce: _nonce(source, nonce_option) } attributes.merge!(options) if _context.assets.subresource_integrity? || attributes.include?(:integrity) attributes[:integrity] ||= _subresource_integrity_value(source, STYLESHEET_EXT) attributes[:crossorigin] ||= CROSSORIGIN_ANONYMOUS end tag.link(**attributes).to_s end end # Generate `img` tag for given source # # It accepts one string representing the name of the asset, if it comes # from the application or third party gems. It also accepts strings # representing absolute URLs in case of public CDN (eg. Bootstrap CDN). # # `alt` Attribute is auto generated from `src`. # You can specify a different value, by passing the `:src` option. # # If the "fingerprint mode" is on, `src` is the fingerprinted # version of the relative URL. # # If the "CDN mode" is on, the `src` is an absolute URL of the # application CDN. # # @param source [String, #url] asset name, absolute URL, or asset object # @param options [Hash] HTML 5 attributes # # @return [Hanami::View::HTML::SafeString] the markup # # @raise [Hanami::Assets::MissingManifestAssetError] if `fingerprint` or # `subresource_integrity` modes are on and the image file is missing # from the manifest # # @since 2.1.0 # # @see Hanami::Assets::Helpers#path # # @example Basic Usage # # <%= image_tag "logo.png" %> # # # <img src="/assets/logo.png" alt="Logo"> # # @example Custom alt Attribute # # <%= image_tag "logo.png", alt: "Application Logo" %> # # # <img src="/assets/logo.png" alt="Application Logo"> # # @example Custom HTML Attributes # # <%= image_tag "logo.png", id: "logo", class: "image" %> # # # <img src="/assets/logo.png" alt="Logo" id="logo" class="image"> # # @example Absolute URL # # <%= image_tag "https://example-cdn.com/images/logo.png" %> # # # <img src="https://example-cdn.com/images/logo.png" alt="Logo"> # # @example Fingerprint Mode # # <%= image_tag "logo.png" %> # # # <img src="/assets/logo-28a6b886de2372ee3922fcaf3f78f2d8.png" alt="Logo"> # # @example CDN Mode # # <%= image_tag "logo.png" %> # # # <img src="https://assets.bookshelf.org/assets/logo-28a6b886de2372ee3922fcaf3f78f2d8.png" alt="Logo"> def image_tag(source, options = {}) options = options.reject { |k, _| k.to_sym == :src } attributes = { src: asset_url(source), alt: _context.inflector.humanize(::File.basename(source, WILDCARD_EXT)) } attributes.merge!(options) tag.img(**attributes) end # Generate `link` tag application favicon. # # If no argument is given, it assumes `favico.ico` from the application. # # It accepts one string representing the name of the asset. # # If the "fingerprint mode" is on, `href` is the fingerprinted version # of the relative URL. # # If the "CDN mode" is on, the `href` is an absolute URL of the # application CDN. # # @param source [String, #url] asset name or asset object # @param options [Hash] HTML 5 attributes # # @return [Hanami::View::HTML::SafeString] the markup # # @raise [Hanami::Assets::MissingManifestAssetError] if `fingerprint` or # `subresource_integrity` modes are on and the favicon is file missing # from the manifest # # @since 2.1.0 # # @see Hanami::Assets::Helpers#path # # @example Basic Usage # # <%= favicon_tag %> # # # <link href="/assets/favicon.ico" rel="shortcut icon" type="image/x-icon"> # # @example Custom Path # # <%= favicon_tag "fav.ico" %> # # # <link href="/assets/fav.ico" rel="shortcut icon" type="image/x-icon"> # # @example Custom HTML Attributes # # <%= favicon_tag "favicon.ico", id: "fav" %> # # # <link id="fav" href="/assets/favicon.ico" rel="shortcut icon" type="image/x-icon"> # # @example Fingerprint Mode # # <%= favicon_tag %> # # # <link href="/assets/favicon-28a6b886de2372ee3922fcaf3f78f2d8.ico" rel="shortcut icon" type="image/x-icon"> # # @example CDN Mode # # <%= favicon_tag %> # # # <link href="https://assets.bookshelf.org/assets/favicon-28a6b886de2372ee3922fcaf3f78f2d8.ico" # rel="shortcut icon" type="image/x-icon"> def favicon_tag(source = DEFAULT_FAVICON, options = {}) options = options.reject { |k, _| k.to_sym == :href } attributes = { href: asset_url(source), rel: FAVICON_REL, type: FAVICON_MIME_TYPE } attributes.merge!(options) tag.link(**attributes) end # Generate `video` tag for given source # # It accepts one string representing the name of the asset, if it comes # from the application or third party gems. It also accepts strings # representing absolute URLs in case of public CDN (eg. Bootstrap CDN). # # Alternatively, it accepts a block that allows to specify one or more # sources via the `source` tag. # # If the "fingerprint mode" is on, `src` is the fingerprinted # version of the relative URL. # # If the "CDN mode" is on, the `src` is an absolute URL of the # application CDN. # # @param source [String, #url] asset name, absolute URL or asset object # @param options [Hash] HTML 5 attributes # # @return [Hanami::View::HTML::SafeString] the markup # # @raise [Hanami::Assets::MissingManifestAssetError] if `fingerprint` or # `subresource_integrity` modes are on and the video file is missing # from the manifest # # @raise [ArgumentError] if source isn"t specified both as argument or # tag inside the given block # # @since 2.1.0 # # @see Hanami::Assets::Helpers#path # # @example Basic Usage # # <%= video_tag "movie.mp4" %> # # # <video src="/assets/movie.mp4"></video> # # @example Absolute URL # # <%= video_tag "https://example-cdn.com/assets/movie.mp4" %> # # # <video src="https://example-cdn.com/assets/movie.mp4"></video> # # @example Custom HTML Attributes # # <%= video_tag("movie.mp4", autoplay: true, controls: true) %> # # # <video src="/assets/movie.mp4" autoplay="autoplay" controls="controls"></video> # # @example Fallback Content # # <%= # video("movie.mp4") do # "Your browser does not support the video tag" # end # %> # # # <video src="/assets/movie.mp4"> # # Your browser does not support the video tag # # </video> # # @example Tracks # # <%= # video("movie.mp4") do # tag.track(kind: "captions", src: asset_url("movie.en.vtt"), # srclang: "en", label: "English") # end # %> # # # <video src="/assets/movie.mp4"> # # <track kind="captions" src="/assets/movie.en.vtt" srclang="en" label="English"> # # </video> # # @example Without Any Argument # # <%= video_tag %> # # # ArgumentError # # @example Without src And Without Block # # <%= video_tag(content: true) %> # # # ArgumentError # # @example Fingerprint Mode # # <%= video_tag "movie.mp4" %> # # # <video src="/assets/movie-28a6b886de2372ee3922fcaf3f78f2d8.mp4"></video> # # @example CDN Mode # # <%= video_tag "movie.mp4" %> # # # <video src="https://assets.bookshelf.org/assets/movie-28a6b886de2372ee3922fcaf3f78f2d8.mp4"></video> def video_tag(source = nil, options = {}, &blk) options = _source_options(source, options, &blk) tag.video(**options, &blk) end # Generate `audio` tag for given source # # It accepts one string representing the name of the asset, if it comes # from the application or third party gems. It also accepts strings # representing absolute URLs in case of public CDN (eg. Bootstrap CDN). # # Alternatively, it accepts a block that allows to specify one or more # sources via the `source` tag. # # If the "fingerprint mode" is on, `src` is the fingerprinted # version of the relative URL. # # If the "CDN mode" is on, the `src` is an absolute URL of the # application CDN. # # @param source [String, #url] asset name, absolute URL or asset object # @param options [Hash] HTML 5 attributes # # @return [Hanami::View::HTML::SafeString] the markup # # @raise [Hanami::Assets::MissingManifestAssetError] if `fingerprint` or # `subresource_integrity` modes are on and the audio file is missing # from the manifest # # @raise [ArgumentError] if source isn"t specified both as argument or # tag inside the given block # # @since 2.1.0 # # @see Hanami::Assets::Helpers#path # # @example Basic Usage # # <%= audio_tag "song.ogg" %> # # # <audio src="/assets/song.ogg"></audio> # # @example Absolute URL # # <%= audio_tag "https://example-cdn.com/assets/song.ogg" %> # # # <audio src="https://example-cdn.com/assets/song.ogg"></audio> # # @example Custom HTML Attributes # # <%= audio_tag("song.ogg", autoplay: true, controls: true) %> # # # <audio src="/assets/song.ogg" autoplay="autoplay" controls="controls"></audio> # # @example Fallback Content # # <%= # audio("song.ogg") do # "Your browser does not support the audio tag" # end # %> # # # <audio src="/assets/song.ogg"> # # Your browser does not support the audio tag # # </audio> # # @example Tracks # # <%= # audio("song.ogg") do # tag.track(kind: "captions", src: asset_url("song.pt-BR.vtt"), # srclang: "pt-BR", label: "Portuguese") # end # %> # # # <audio src="/assets/song.ogg"> # # <track kind="captions" src="/assets/song.pt-BR.vtt" srclang="pt-BR" label="Portuguese"> # # </audio> # # @example Without Any Argument # # <%= audio_tag %> # # # ArgumentError # # @example Without src And Without Block # # <%= audio_tag(controls: true) %> # # # ArgumentError # # @example Fingerprint Mode # # <%= audio_tag "song.ogg" %> # # # <audio src="/assets/song-28a6b886de2372ee3922fcaf3f78f2d8.ogg"></audio> # # @example CDN Mode # # <%= audio_tag "song.ogg" %> # # # <audio src="https://assets.bookshelf.org/assets/song-28a6b886de2372ee3922fcaf3f78f2d8.ogg"></audio> def audio_tag(source = nil, options = {}, &blk) options = _source_options(source, options, &blk) tag.audio(**options, &blk) end # It generates the relative or absolute URL for the given asset. # It automatically decides if it has to use the relative or absolute # depending on the configuration and current environment. # # Absolute URLs are returned as they are. # # It can be the name of the asset, coming from the sources or third party # gems. # # If Fingerprint mode is on, it returns the fingerprinted path of the source # # If CDN mode is on, it returns the absolute URL of the asset. # # @param source [String, #url] the asset name or asset object # # @return [String] the asset path # # @raise [Hanami::Assets::MissingManifestAssetError] if `fingerprint` or # `subresource_integrity` modes are on and the asset is missing # from the manifest # # @since 2.1.0 # # @example Basic Usage # # <%= asset_url "application.js" %> # # # "/assets/application.js" # # @example Alias # # <%= asset_url "application.js" %> # # # "/assets/application.js" # # @example Absolute URL # # <%= asset_url "https://code.jquery.com/jquery-2.1.4.min.js" %> # # # "https://code.jquery.com/jquery-2.1.4.min.js" # # @example Fingerprint Mode # # <%= asset_url "application.js" %> # # # "/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.js" # # @example CDN Mode # # <%= asset_url "application.js" %> # # # "https://assets.bookshelf.org/assets/application-28a6b886de2372ee3922fcaf3f78f2d8.js" def asset_url(source) return source.url if source.respond_to?(:url) return source if _absolute_url?(source) _context.assets[source].url end # Random per request nonce value for Content Security Policy (CSP) rules. # # If the `Hanami::Middleware::ContentSecurityPolicyNonce` middleware is # in use, this helper returns the nonce value for the current request # or `nil` otherwise. # # For this policy to work in the browser, you have to add the `'nonce'` # placeholder to the script and/or style source policy rule. It will be # substituted by the current nonce value like `'nonce-A12OggyZ'. # # @return [String, nil] nonce value of the current request # # @since 2.3.0 # # @example App configuration # # config.middleware.use Hanami::Middleware::ContentSecurityPolicyNonce # config.actions.content_security_policy[:script_src] = "'self' 'nonce'" # config.actions.content_security_policy[:style_src] = "'self' 'nonce'" # # @example View helper # # <script nonce="<%= content_security_policy_nonce %>"> def content_security_policy_nonce return unless _context.request? _context.request.env[CONTENT_SECURITY_POLICY_NONCE_REQUEST_KEY] end private # @since 2.1.0 # @api private def _safe_tags(*sources, &blk) ::Hanami::View::HTML::SafeString.new( sources.map(&blk).join(NEW_LINE_SEPARATOR) ) end # @since 2.1.0 # @api private def _typed_url(source, ext) source = "#{source}#{ext}" if source.is_a?(String) && _append_extension?(source, ext) asset_url(source) end # @api private def _subresource_integrity_value(source, ext) return if _absolute_url?(source) source = "#{source}#{ext}" unless /#{Regexp.escape(ext)}\z/.match?(source) _context.assets[source].sri end # @since 2.1.0 # @api private def _absolute_url?(source) ABSOLUTE_URL_MATCHER.match?(source.respond_to?(:url) ? source.url : source) end # @since 1.2.0 # @api private def _crossorigin?(source) return false unless _absolute_url?(source) _context.assets.crossorigin?(source) end # @since 2.3.0 # @api private def _nonce(source, nonce_option) if nonce_option == false nil elsif nonce_option == true || (nonce_option.nil? && !_absolute_url?(source)) content_security_policy_nonce else nonce_option end end # @since 2.1.0 # @api private def _source_options(src, options, &blk) options ||= {} if src.respond_to?(:to_hash) options = src.to_hash elsif src options[:src] = asset_url(src) end if !options[:src] && !blk raise ArgumentError.new("You should provide a source via `src` option or with a `source` HTML tag") end options end # @since 1.1.0 # @api private def _append_extension?(source, ext) source !~ QUERY_STRING_MATCHER && source !~ /#{Regexp.escape(ext)}\z/ end end end end # rubocop:enable Metrics/ModuleLength
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/helpers/form_helper.rb
lib/hanami/helpers/form_helper.rb
# frozen_string_literal: true require "hanami/view" module Hanami module Helpers # Helper methods for generating HTML forms. # # These helpers will be automatically available in your view templates, part classes and scope # classes. # # This module provides one primary method: {#form_for}, yielding an HTML form builder. This # integrates with request params and template locals to populate the form with appropriate # values. # # @api public # @since 2.1.0 module FormHelper require_relative "form_helper/form_builder" # Default HTTP method for form # # @since 2.1.0 # @api private DEFAULT_METHOD = "POST" # Default charset # # @since 2.1.0 # @api private DEFAULT_CHARSET = "utf-8" # CSRF Token session key # # This name of this key is shared with the hanami and hanami-controller gems. # # @since 2.1.0 # @api private CSRF_TOKEN = :_csrf_token include Hanami::View::Helpers::TagHelper # Yields a form builder for constructing an HTML form and returns the resulting form string. # # See {FormHelper::FormBuilder} for the methods for building the form's fields. # # @overload form_for(base_name, url, values: _form_for_values, params: _form_for_params, **attributes) # Builds the form using the given base name for all fields. # # @param base_name [String] the base # @param url [String] the URL for submitting the form # @param values [Hash] values to be used for populating form field values; optional, # defaults to the template's locals or to a part's `{name => self}` # @param params [Hash] request param values to be used for populating form field values; # these are used in preference over the `values`; optional, defaults to the current # request's params # @param attributes [Hash] the HTML attributes for the form tag # @yieldparam [FormHelper::FormBuilder] f the form builder # # @overload form_for(url, values: _form_for_values, params: _form_for_params, **attributes) # @param url [String] the URL for submitting the form # @param values [Hash] values to be used for populating form field values; optional, # defaults to the template's locals or to a part's `{name => self}` # @param params [Hash] request param values to be used for populating form field values; # these are used in preference over the `values`; optional, defaults to the current # request's params # @param attributes [Hash] the HTML attributes for the form tag # @yieldparam [FormHelper::FormBuilder] f the form builder # # @return [String] the form HTML # # @see FormHelper # @see FormHelper::FormBuilder # # @example Basic usage # <%= form_for("book", "/books", class: "form-horizontal") do |f| %> # <div> # <%= f.label "title" %> # <%= f.text_field "title", class: "form-control" %> # </div> # # <%= f.submit "Create" %> # <% end %> # # => # <form action="/books" method="POST" accept-charset="utf-8" class="form-horizontal"> # <input type="hidden" name="_csrf_token" value="920cd5bfaecc6e58368950e790f2f7b4e5561eeeab230aa1b7de1b1f40ea7d5d"> # <div> # <label for="book-title">Title</label> # <input type="text" name="book[title]" id="book-title" value="Test Driven Development"> # </div> # # <button type="submit">Create</button> # </form> # # @example Without base name # # <%= form_for("/books", class: "form-horizontal") do |f| %> # <div> # <%= f.label "books.title" %> # <%= f.text_field "books.title", class: "form-control" %> # </div> # # <%= f.submit "Create" %> # <% end %> # # => # <form action="/books" method="POST" accept-charset="utf-8" class="form-horizontal"> # <input type="hidden" name="_csrf_token" value="920cd5bfaecc6e58368950e790f2f7b4e5561eeeab230aa1b7de1b1f40ea7d5d"> # <div> # <label for="book-title">Title</label> # <input type="text" name="book[title]" id="book-title" value="Test Driven Development"> # </div> # # <button type="submit">Create</button> # </form> # # @example Method override # <%= form_for("/books/123", method: :put) do |f| # <%= f.text_field "book.title" %> # <%= f.submit "Update" %> # <% end %> # # => # <form action="/books/123" accept-charset="utf-8" method="POST"> # <input type="hidden" name="_method" value="PUT"> # <input type="hidden" name="_csrf_token" value="920cd5bfaecc6e58368950e790f2f7b4e5561eeeab230aa1b7de1b1f40ea7d5d"> # <input type="text" name="book[title]" id="book-title" value="Test Driven Development"> # # <button type="submit">Update</button> # </form> # # @example Overriding values # <%= form_for("/songs", values: {song: {title: "Envision"}}) do |f| %> # <%= f.text_field "song.title" %> # <%= f.submit "Create" %> # <%= end %> # # => # <form action="/songs" accept-charset="utf-8" method="POST"> # <input type="hidden" name="_csrf_token" value="920cd5bfaecc6e58368950e790f2f7b4e5561eeeab230aa1b7de1b1f40ea7d5d"> # <input type="text" name="song[title]" id="song-title" value="Envision"> # # <button type="submit">Create</button> # </form> # # @api public # @since 2.1.0 def form_for(base_name, url = nil, values: _form_for_values, params: _form_for_params, **attributes) url, base_name = base_name, nil if url.nil? values = Values.new(values: values, params: params, csrf_token: _form_csrf_token) builder = FormBuilder.new( base_name: base_name, values: values, inflector: _context.inflector, form_attributes: attributes ) content = (block_given? ? yield(builder) : "").html_safe builder.call(content, action: url, **attributes) end # Returns CSRF meta tags for use via unobtrusive JavaScript (UJS) libraries. # # @return [String, nil] the tags, if a CSRF token is available, or nil # # @example # csrf_meta_tags # # => # <meta name="csrf-param" content="_csrf_token"> # <meta name="csrf-token" content="4a038be85b7603c406dcbfad4b9cdf91ec6ca138ed6441163a07bb0fdfbe25b5"> # # @api public # @since 2.1.0 def csrf_meta_tags return unless (token = _form_csrf_token) tag.meta(name: "csrf-param", content: CSRF_TOKEN) + tag.meta(name: "csrf-token", content: token) end # @api private # @since 2.1.0 def _form_for_values if respond_to?(:_locals) # Scope _locals elsif respond_to?(:_name) # Part {_name => self} else {} end end # @api private # @since 2.1.0 def _form_for_params _context.request.params end # @since 2.1.0 # @api private def _form_csrf_token return unless _context.request.session_enabled? _context.csrf_token end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/helpers/form_helper/values.rb
lib/hanami/helpers/form_helper/values.rb
# frozen_string_literal: true module Hanami module Helpers module FormHelper # Values from params and form helpers. # # It's responsible to populate input values with data coming from params # and inline values specified via form helpers like `text_field`. # # @since 2.1.0 # @api private class Values # @since 2.1.0 # @api private GET_SEPARATOR = "." # @api private # @since 2.1.0 attr_reader :csrf_token # @since 2.1.0 # @api private def initialize(values: {}, params: {}, csrf_token: nil) @values = values.to_h @params = params.to_h @csrf_token = csrf_token end # Returns the value (if present) for the given key. # Nested values are expressed with an array if symbols. # # @since 2.1.0 # @api private def get(*keys) get_from_params(*keys) || get_from_values(*keys) end private # @since 2.1.0 # @api private def get_from_params(*keys) keys.map! { |key| /\A\d+\z/.match?(key.to_s) ? key.to_s.to_i : key } @params.dig(*keys) end # @since 2.1.0 # @api private def get_from_values(*keys) head, *tail = *keys result = @values[head] tail.each do |k| break if result.nil? result = dig(result, k) end result end # @since 2.1.0 # @api private def dig(base, key) case base when ::Hash then base[key] when Array then base[key.to_s.to_i] when ->(r) { r.respond_to?(key) } then base.public_send(key) end end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/helpers/form_helper/form_builder.rb
lib/hanami/helpers/form_helper/form_builder.rb
# frozen_string_literal: true require "hanami/view" require_relative "values" module Hanami module Helpers module FormHelper # A range of convenient methods for building the fields within an HTML form, integrating with # request params and template locals to populate the fields with appropriate values. # # @see FormHelper#form_for # # @api public # @since 2.1.0 class FormBuilder # Set of HTTP methods that are understood by web browsers # # @since 2.1.0 # @api private BROWSER_METHODS = %w[GET POST].freeze private_constant :BROWSER_METHODS # Set of HTTP methods that should NOT generate CSRF token # # @since 2.1.0 # @api private EXCLUDED_CSRF_METHODS = %w[GET].freeze private_constant :EXCLUDED_CSRF_METHODS # Separator for accept attribute of file input # # @since 2.1.0 # @api private # # @see #file_input ACCEPT_SEPARATOR = "," private_constant :ACCEPT_SEPARATOR # Default value for unchecked check box # # @since 2.1.0 # @api private # # @see #check_box DEFAULT_UNCHECKED_VALUE = "0" private_constant :DEFAULT_UNCHECKED_VALUE # Default value for checked check box # # @since 2.1.0 # @api private # # @see #check_box DEFAULT_CHECKED_VALUE = "1" private_constant :DEFAULT_CHECKED_VALUE # Input name separator # # @since 2.1.0 # @api private INPUT_NAME_SEPARATOR = "." private_constant :INPUT_NAME_SEPARATOR # Empty string # # @since 2.1.0 # @api private # # @see #password_field EMPTY_STRING = "" private_constant :EMPTY_STRING include Hanami::View::Helpers::EscapeHelper include Hanami::View::Helpers::TagHelper # @api private # @since 2.1.0 attr_reader :base_name private :base_name # @api private # @since 2.1.0 attr_reader :values private :values # @api private # @since 2.1.0 attr_reader :inflector private :inflector # @api private # @since 2.1.0 attr_reader :form_attributes private :form_attributes # Returns a new form builder. # # @param inflector [Dry::Inflector] the app inflector # @param base_name [String, nil] the base name to use for all fields in the form # @param values [Hanami::Helpers::FormHelper::Values] the values for the form # # @return [self] # # @see Hanami::Helpers::FormHelper#form_for # # @api private # @since 2.1.0 def initialize(inflector:, form_attributes:, base_name: nil, values: Values.new) @base_name = base_name @values = values @form_attributes = form_attributes @inflector = inflector end # @api private # @since 2.1.0 def call(content, **attributes) attributes["accept-charset"] ||= DEFAULT_CHARSET method_override, original_form_method = _form_method(attributes) csrf_token, token = _csrf_token(values, attributes) tag.form(**attributes) do (+"").tap { |inner| inner << input(type: "hidden", name: "_method", value: original_form_method) if method_override inner << input(type: "hidden", name: "_csrf_token", value: token) if csrf_token inner << content }.html_safe end end # Applies the base input name to all fields within the given block. # # This can be helpful when generating a set of nested fields. # # This is a convenience only. You can achieve the same result by including the base name at # the beginning of each input name. # # @param name [String] the base name to be used for all fields in the block # @yieldparam [FormBuilder] the form builder for the nested fields # # @example Basic usage # <% f.fields_for "address" do |fa| %> # <%= fa.text_field "street" %> # <%= fa.text_field "suburb" %> # <% end %> # # # A convenience for: # # <%= f.text_field "address.street" %> # # <%= f.text_field "address.suburb" %> # # => # <input type="text" name="delivery[customer_name]" id="delivery-customer-name" value=""> # <input type="text" name="delivery[address][street]" id="delivery-address-street" value=""> # # @example Multiple levels of nesting # <% f.fields_for "address" do |fa| %> # <%= fa.text_field "street" %> # # <% fa.fields_for "location" do |fl| %> # <%= fl.text_field "city" %> # <% end %> # <% end %> # # => # <input type="text" name="delivery[address][street]" id="delivery-address-street" value=""> # <input type="text" name="delivery[address][location][city]" id="delivery-address-location-city" value=""> # # @api public # @since 2.1.0 def fields_for(name, *yield_args) new_base_name = [base_name, name.to_s].compact.join(INPUT_NAME_SEPARATOR) builder = self.class.new( base_name: new_base_name, values: values, form_attributes: form_attributes, inflector: inflector ) yield(builder, *yield_args) end # Yields to the given block for each element in the matching collection value, and applies # the base input name to all fields within the block. # # Use this whenever generating form fields for an collection of nested fields. # # @param name [String] the input name, also used as the base input name for all fields # within the block # @yieldparam [FormBuilder] the form builder for the nested fields # @yieldparam [Integer] the index of the iteration over the collection, starting from zero # @yieldparam [Object] the value of the element from the collection # # @example Basic usage # <% f.fields_for_collection("addresses") do |fa| %> # <%= fa.text_field("street") %> # <% end %> # # => # <input type="text" name="delivery[addresses][][street]" id="delivery-address-0-street" value=""> # <input type="text" name="delivery[addresses][][street]" id="delivery-address-1-street" value=""> # # @example Yielding index and value # <% f.fields_for_collection("bill.addresses") do |fa, i, address| %> # <div class="form-group"> # Address id: <%= address.id %> # <%= fa.label("street") %> # <%= fa.text_field("street", data: {index: i.to_s}) %> # </div> # <% end %> # # => # <div class="form-group"> # Address id: 23 # <label for="bill-addresses-0-street">Street</label> # <input type="text" name="bill[addresses][][street]" id="bill-addresses-0-street" value="5th Ave" data-index="0"> # </div> # <div class="form-group"> # Address id: 42 # <label for="bill-addresses-1-street">Street</label> # <input type="text" name="bill[addresses][][street]" id="bill-addresses-1-street" value="4th Ave" data-index="1"> # </div> # # @api public # @since 2.1.0 def fields_for_collection(name, &block) _value(name).each_with_index do |value, index| fields_for("#{name}.#{index}", index, value, &block) end end # Returns a label tag. # # @return [String] the tag # # @overload label(field_name, **attributes) # Returns a label tag for the given field name, with a humanized version of the field name # as the tag's content. # # @param field_name [String] the field name # @param attributes [Hash] the tag attributes # # @example # <%= f.label("book.extended_title") %> # # => <label for="book-extended-title">Extended title</label> # # @example HTML attributes # <%= f.label("book.title", class: "form-label") %> # # => <label for="book-title" class="form-label">Title</label> # # @overload label(content, **attributes) # Returns a label tag for the field name given as `for:`, with the given content string as # the tag's content. # # @param content [String] the tag's content # @param for [String] the field name # @param attributes [Hash] the tag attributes # # @example # <%= f.label("Title", for: "book.extended_title") %> # # => <label for="book-extended-title">Title</label> # # f.label("book.extended_title", for: "ext-title") # # => <label for="ext-title">Extended title</label> # # @overload label(field_name, **attributes, &block) # Returns a label tag for the given field name, with the return value of the given block # as the tag's content. # # @param field_name [String] the field name # @param attributes [Hash] the tag attributes # @yieldreturn [String] the tag content # # @example # <%= f.label for: "book.free_shipping" do %> # Free shipping # <abbr title="optional" aria-label="optional">*</abbr> # <% end %> # # # => # <label for="book-free-shipping"> # Free shipping # <abbr title="optional" aria-label="optional">*</abbr> # </label> # # @api public # @since 2.1.0 def label(content = nil, **attributes, &block) for_attribute_given = attributes.key?(:for) attributes[:for] = _input_id(attributes[:for] || content) if content && !for_attribute_given content = inflector.humanize(content.to_s.split(INPUT_NAME_SEPARATOR).last) end tag.label(content, **attributes, &block) end # @overload fieldset(**attributes, &block) # Returns a fieldset tag. # # @param attributes [Hash] the tag's HTML attributes # @yieldreturn [String] the tag's content # # @return [String] the tag # # @example # <%= f.fieldset do %> # <%= f.legend("Author") %> # <%= f.label("author.name") %> # <%= f.text_field("author.name") %> # <% end %> # # # => # <fieldset> # <legend>Author</legend> # <label for="book-author-name">Name</label> # <input type="text" name="book[author][name]" id="book-author-name" value=""> # </fieldset> # # @since 2.1.0 # @api public def fieldset(...) # This is here only for documentation purposes tag.fieldset(...) end # Returns the tags for a check box. # # When editing a resource, the form automatically assigns the `checked` HTML attribute for # the check box tag. # # Returns a hidden input tag in preceding the check box input tag. This ensures that # unchecked values are submitted with the form. # # @param name [String] the input name # @param attributes [Hash] the HTML attributes for the check box tag # @option attributes [String] :checked_value (defaults to "1") # @option attributes [String] :unchecked_value (defaults to "0") # # @return [String] the tags # # @example Basic usage # f.check_box("delivery.free_shipping") # # # => # <input type="hidden" name="delivery[free_shipping]" value="0"> # <input type="checkbox" name="delivery[free_shipping]" id="delivery-free-shipping" value="1"> # # @example HTML Attributes # f.check_box("delivery.free_shipping", class: "form-check-input") # # => # <input type="hidden" name="delivery[free_shipping]" value="0"> # <input type="checkbox" name="delivery[free_shipping]" id="delivery-free-shipping" value="1" class="form-check-input"> # # @example Specifying checked and unchecked values # f.check_box("delivery.free_shipping", checked_value: "true", unchecked_value: "false") # # => # <input type="hidden" name="delivery[free_shipping]" value="false"> # <input type="checkbox" name="delivery[free_shipping]" id="delivery-free-shipping" value="true"> # # @example Automatic "checked" attribute # # Given the request params: # # {delivery: {free_shipping: "1"}} # f.check_box("delivery.free_shipping") # # => # <input type="hidden" name="delivery[free_shipping]" value="0"> # <input type="checkbox" name="delivery[free_shipping]" id="delivery-free-shipping" value="1" checked="checked"> # # @example Forcing the "checked" attribute # # Given the request params: # # {delivery: {free_shipping: "0"}} # f.check_box("deliver.free_shipping", checked: "checked") # # => # <input type="hidden" name="delivery[free_shipping]" value="0"> # <input type="checkbox" name="delivery[free_shipping]" id="delivery-free-shipping" value="1" checked="checked"> # # @example Multiple check boxes for an array of values # f.check_box("book.languages", name: "book[languages][]", value: "italian", id: nil) # f.check_box("book.languages", name: "book[languages][]", value: "english", id: nil) # # => # <input type="checkbox" name="book[languages][]" value="italian"> # <input type="checkbox" name="book[languages][]" value="english"> # # @example Automatic "checked" attribute for an array of values # # Given the request params: # # {book: {languages: ["italian"]}} # f.check_box("book.languages", name: "book[languages][]", value: "italian", id: nil) # f.check_box("book.languages", name: "book[languages][]", value: "english", id: nil) # # => # <input type="checkbox" name="book[languages][]" value="italian" checked="checked"> # <input type="checkbox" name="book[languages][]" value="english"> # # @api public # @since 2.1.0 def check_box(name, **attributes) (+"").tap { |output| output << _hidden_field_for_check_box(name, attributes).to_s output << input(**_attributes_for_check_box(name, attributes)) }.html_safe end # Returns a color input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.color_field("user.background") # => <input type="color" name="user[background]" id="user-background" value=""> # # @example HTML Attributes # f.color_field("user.background", class: "form-control") # => <input type="color" name="user[background]" id="user-background" value="" class="form-control"> # # @api public # @since 2.1.0 def color_field(name, **attributes) input(**_attributes(:color, name, attributes)) end # Returns a date input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.date_field("user.birth_date") # # => <input type="date" name="user[birth_date]" id="user-birth-date" value=""> # # @example HTML Attributes # f.date_field("user.birth_date", class: "form-control") # => <input type="date" name="user[birth_date]" id="user-birth-date" value="" class="form-control"> # # @api public # @since 2.1.0 def date_field(name, **attributes) input(**_attributes(:date, name, attributes)) end # Returns a datetime input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.datetime_field("delivery.delivered_at") # => <input type="datetime" name="delivery[delivered_at]" id="delivery-delivered-at" value=""> # # @example HTML Attributes # f.datetime_field("delivery.delivered_at", class: "form-control") # => <input type="datetime" name="delivery[delivered_at]" id="delivery-delivered-at" value="" class="form-control"> # # @api public # @since 2.1.0 def datetime_field(name, **attributes) input(**_attributes(:datetime, name, attributes)) end # Returns a datetime-local input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.datetime_local_field("delivery.delivered_at") # => <input type="datetime-local" name="delivery[delivered_at]" id="delivery-delivered-at" value=""> # # @example HTML Attributes # f.datetime_local_field("delivery.delivered_at", class: "form-control") # => <input type="datetime-local" name="delivery[delivered_at]" id="delivery-delivered-at" value="" class="form-control"> # # @api public # @since 2.1.0 def datetime_local_field(name, **attributes) input(**_attributes(:"datetime-local", name, attributes)) end # Returns a time input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.time_field("book.release_hour") # => <input type="time" name="book[release_hour]" id="book-release-hour" value=""> # # @example HTML Attributes # f.time_field("book.release_hour", class: "form-control") # => <input type="time" name="book[release_hour]" id="book-release-hour" value="" class="form-control"> # # @api public # @since 2.1.0 def time_field(name, **attributes) input(**_attributes(:time, name, attributes)) end # Returns a month input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.month_field("book.release_month") # => <input type="month" name="book[release_month]" id="book-release-month" value=""> # # @example HTML Attributes # f.month_field("book.release_month", class: "form-control") # => <input type="month" name="book[release_month]" id="book-release-month" value="" class="form-control"> # # @api public # @since 2.1.0 def month_field(name, **attributes) input(**_attributes(:month, name, attributes)) end # Returns a week input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.week_field("book.release_week") # => <input type="week" name="book[release_week]" id="book-release-week" value=""> # # @example HTML Attributes # f.week_field("book.release_week", class: "form-control") # => <input type="week" name="book[release_week]" id="book-release-week" value="" class="form-control"> # # @api public # @since 2.1.0 def week_field(name, **attributes) input(**_attributes(:week, name, attributes)) end # Returns an email input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.email_field("user.email") # => <input type="email" name="user[email]" id="user-email" value=""> # # @example HTML Attributes # f.email_field("user.email", class: "form-control") # => <input type="email" name="user[email]" id="user-email" value="" class="form-control"> # # @api public # @since 2.1.0 def email_field(name, **attributes) input(**_attributes(:email, name, attributes)) end # Returns a URL input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.url_field("user.website") # => <input type="url" name="user[website]" id="user-website" value=""> # # @example HTML Attributes # f.url_field("user.website", class: "form-control") # => <input type="url" name="user[website]" id="user-website" value="" class="form-control"> # # @api public # @since 2.1.0 def url_field(name, **attributes) attributes[:value] = sanitize_url(attributes.fetch(:value) { _value(name) }) input(**_attributes(:url, name, attributes)) end # Returns a telephone input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example # f.tel_field("user.telephone") # => <input type="tel" name="user[telephone]" id="user-telephone" value=""> # # @example HTML Attributes # f.tel_field("user.telephone", class: "form-control") # => <input type="tel" name="user[telephone]" id="user-telephone" value="" class="form-control"> # # @api public # @since 2.1.0 def tel_field(name, **attributes) input(**_attributes(:tel, name, attributes)) end # Returns a hidden input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example # f.hidden_field("delivery.customer_id") # => <input type="hidden" name="delivery[customer_id]" id="delivery-customer-id" value=""> # # @api public # @since 2.1.0 def hidden_field(name, **attributes) input(**_attributes(:hidden, name, attributes)) end # Returns a file input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # @option attributes [String, Array] :accept Optional set of accepted MIME Types # @option attributes [Boolean] :multiple allow multiple file upload # # @return [String] the tag # # @example Basic usage # f.file_field("user.avatar") # => <input type="file" name="user[avatar]" id="user-avatar"> # # @example HTML Attributes # f.file_field("user.avatar", class: "avatar-upload") # => <input type="file" name="user[avatar]" id="user-avatar" class="avatar-upload"> # # @example Accepted MIME Types # f.file_field("user.resume", accept: "application/pdf,application/ms-word") # => <input type="file" name="user[resume]" id="user-resume" accept="application/pdf,application/ms-word"> # # f.file_field("user.resume", accept: ["application/pdf", "application/ms-word"]) # => <input type="file" name="user[resume]" id="user-resume" accept="application/pdf,application/ms-word"> # # @example Accept multiple file uploads # f.file_field("user.resume", multiple: true) # => <input type="file" name="user[resume]" id="user-resume" multiple="multiple"> # # @api public # @since 2.1.0 def file_field(name, **attributes) form_attributes[:enctype] = "multipart/form-data" attributes[:accept] = Array(attributes[:accept]).join(ACCEPT_SEPARATOR) if attributes.key?(:accept) attributes = {type: :file, name: _input_name(name), id: _input_id(name), **attributes} input(**attributes) end # Returns a number input tag. # # For this tag, you can make use of the `max`, `min`, and `step` HTML attributes. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.number_field("book.percent_read") # => <input type="number" name="book[percent_read]" id="book-percent-read" value=""> # # @example Advanced attributes # f.number_field("book.percent_read", min: 1, max: 100, step: 1) # => <input type="number" name="book[percent_read]" id="book-percent-read" value="" min="1" max="100" step="1"> # # @api public # @since 2.1.0 def number_field(name, **attributes) input(**_attributes(:number, name, attributes)) end # Returns a range input tag. # # For this tag, you can make use of the `max`, `min`, and `step` HTML attributes. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.range_field("book.discount_percentage") # => <input type="range" name="book[discount_percentage]" id="book-discount-percentage" value=""> # # @example Advanced attributes # f.range_field("book.discount_percentage", min: 1, max: 1'0, step: 1) # => <input type="number" name="book[discount_percentage]" id="book-discount-percentage" value="" min="1" max="100" step="1"> # # @api public # @since 2.1.0 def range_field(name, **attributes) input(**_attributes(:range, name, attributes)) end # Returns a textarea tag. # # @param name [String] the input name # @param content [String] the content of the textarea # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.text_area("user.hobby") # => <textarea name="user[hobby]" id="user-hobby"></textarea> # # f.text_area "user.hobby", "Football" # => # <textarea name="user[hobby]" id="user-hobby"> # Football</textarea> # # @example HTML attributes # f.text_area "user.hobby", class: "form-control" # => <textarea name="user[hobby]" id="user-hobby" class="form-control"></textarea> # # @api public # @since 2.1.0 def text_area(name, content = nil, **attributes) if content.respond_to?(:to_hash) attributes = content content = nil end attributes = {name: _input_name(name), id: _input_id(name), **attributes} tag.textarea(content || _value(name), **attributes) end # Returns a text input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.text_field("user.first_name") # => <input type="text" name="user[first_name]" id="user-first-name" value=""> # # @example HTML Attributes # f.text_field("user.first_name", class: "form-control") # => <input type="text" name="user[first_name]" id="user-first-name" value="" class="form-control"> # # @api public # @since 2.1.0 def text_field(name, **attributes) input(**_attributes(:text, name, attributes)) end alias_method :input_text, :text_field # Returns a search input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.search_field("search.q") # => <input type="search" name="search[q]" id="search-q" value=""> # # @example HTML Attributes # f.search_field("search.q", class: "form-control") # => <input type="search" name="search[q]" id="search-q" value="" class="form-control"> # # @api public # @since 2.1.0 def search_field(name, **attributes) input(**_attributes(:search, name, attributes)) end # Returns a radio input tag. # # When editing a resource, the form automatically assigns the `checked` HTML attribute for # the tag. # # @param name [String] the input name # @param value [String] the input value # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.radio_button("book.category", "Fiction") # f.radio_button("book.category", "Non-Fiction") # # => # <input type="radio" name="book[category]" value="Fiction"> # <input type="radio" name="book[category]" value="Non-Fiction"> # # @example HTML Attributes # f.radio_button("book.category", "Fiction", class: "form-check") # f.radio_button("book.category", "Non-Fiction", class: "form-check") # # => # <input type="radio" name="book[category]" value="Fiction" class="form-check"> # <input type="radio" name="book[category]" value="Non-Fiction" class="form-check"> # # @example Automatic checked value # # Given the request params: # # {book: {category: "Non-Fiction"}} # f.radio_button("book.category", "Fiction") # f.radio_button("book.category", "Non-Fiction") # # => # <input type="radio" name="book[category]" value="Fiction"> # <input type="radio" name="book[category]" value="Non-Fiction" checked="checked"> # # @api public # @since 2.1.0 def radio_button(name, value, **attributes) attributes = {type: :radio, name: _input_name(name), value: value, **attributes} attributes[:checked] = true if _value(name).to_s == value.to_s input(**attributes) end # Returns a password input tag. # # @param name [String] the input name # @param attributes [Hash] the tag's HTML attributes # # @return [String] the tag # # @example Basic usage # f.password_field("signup.password") # => <input type="password" name="signup[password]" id="signup-password" value=""> # # @api public # @since 2.1.0 def password_field(name, **attributes) attrs = {type: :password, name: _input_name(name), id: _input_id(name), value: nil, **attributes} attrs[:value] = EMPTY_STRING if attrs[:value].nil?
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
true
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/settings/env_store.rb
lib/hanami/settings/env_store.rb
# frozen_string_literal: true require "dry/core/constants" module Hanami class Settings # The default store for {Hanami::Settings}, loading setting values from `ENV`. # # If your app loads the dotenv gem, then `ENV` will also be populated from various `.env` files when # you subclass `Hanami::App`. # # @since 2.0.0 # @api private class EnvStore NO_ARG = Object.new.freeze attr_reader :store, :hanami_env def initialize(store: ENV, hanami_env: Hanami.env) @store = store @hanami_env = hanami_env end def fetch(name, default_value = NO_ARG, &block) name = name.to_s.upcase args = default_value.eql?(NO_ARG) ? [name] : [name, default_value] store.fetch(*args, &block) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/middleware/public_errors_app.rb
lib/hanami/middleware/public_errors_app.rb
# frozen_string_literal: true require "rack" module Hanami module Middleware # The errors app given to {Hanami::Middleware::RenderErrors}, which renders error responses # from HTML pages kept in `public/` as simple JSON structures. # # @see Hanami::Middleware::RenderErrors # # @api private # @since 2.1.0 class PublicErrorsApp # @api private # @since 2.1.0 attr_reader :public_path # @api private # @since 2.1.0 def initialize(public_path) @public_path = public_path end # @api private # @since 2.1.0 def call(env) request = Rack::Request.new(env) status = request.path_info[1..].to_i content_type = request.get_header("HTTP_ACCEPT") default_body = { status: status, error: Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500]) } render(status, content_type, default_body) end private def render(status, content_type, default_body) body, rendered_content_type = render_content(status, content_type, default_body) [ status, { "Content-Type" => "#{rendered_content_type}; charset=utf-8", "Content-Length" => body.bytesize.to_s }, [body] ] end def render_content(status, content_type, default_body) if content_type.to_s.start_with?("application/json") require "json" [JSON.generate(default_body), "application/json"] else [render_html_content(status, default_body), "text/html"] end end def render_html_content(status, default_body) path = "#{public_path}/#{status}.html" if File.exist?(path) File.read(path) else default_body[:error] end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/middleware/assets.rb
lib/hanami/middleware/assets.rb
# frozen_string_literal: true require "rack/static" module Hanami module Middleware class Assets < Rack::Static def initialize(app, options = {}, config: Hanami.app.config) root = config.actions.public_directory urls = [config.assets.path_prefix] defaults = { root: root, urls: urls } super(app, defaults.merge(options)) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/middleware/render_errors.rb
lib/hanami/middleware/render_errors.rb
# frozen_string_literal: true require "rack" # rubocop:disable Lint/RescueException module Hanami module Middleware # Rack middleware that rescues errors raised by the app renders friendly error responses, via a # given "errors app". # # By default, this is enabled only in production mode. # # @see Hanami::Config#render_errors # @see Hanani::Middleware::PublicErrorsApp # # @api private # @since 2.1.0 class RenderErrors # @api private # @since 2.1.0 class RenderableException attr_reader :exception attr_reader :responses # @api private # @since 2.1.0 def initialize(exception, responses:) @exception = exception @responses = responses end # @api private # @since 2.1.0 def rescue_response? responses.key?(exception.class.name) end # @api private # @since 2.1.0 def status_code Rack::Utils.status_code(responses[exception.class.name]) end end # @api private # @since 2.1.0 def initialize(app, config, errors_app) @app = app @config = config @errors_app = errors_app end # @api private # @since 2.1.0 def call(env) @app.call(env) rescue Exception => exception raise unless @config.render_errors render_exception(env, exception) end private def render_exception(env, exception) request = Rack::Request.new(env) renderable = RenderableException.new(exception, responses: @config.render_error_responses) status = renderable.status_code request.path_info = "/#{status}" request.set_header(Rack::REQUEST_METHOD, "GET") @errors_app.call(request.env) rescue Exception => failsafe_error # rubocop:disable Style/StderrPuts $stderr.puts "Error during exception rendering: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}" # rubocop:enable Style/StderrPuts [ 500, {"Content-Type" => "text/plain; charset=utf-8"}, ["Internal Server Error"] ] end end end end # rubocop:enable Lint/RescueException
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/middleware/content_security_policy_nonce.rb
lib/hanami/middleware/content_security_policy_nonce.rb
# frozen_string_literal: true require "rack" require "securerandom" require_relative "../constants" module Hanami module Middleware # Generates a random per request nonce value like `mSMnSwfVZVe+LyQy1SPCGw==`, stores it as # `"hanami.content_security_policy_nonce"` in the Rack environment, and replaces all occurrences # of `'nonce'` in the `Content-Security-Policy header with the actual nonce value for the # request, e.g. `'nonce-mSMnSwfVZVe+LyQy1SPCGw=='`. # # @see Hanami::Middleware::ContentSecurityPolicyNonce # # @api private # @since 2.3.0 class ContentSecurityPolicyNonce # @api private # @since 2.3.0 def initialize(app) @app = app end # @api private # @since 2.3.0 def call(env) return @app.call(env) unless Hanami.app.config.actions.content_security_policy? args = nonce_generator.arity == 1 ? [Rack::Request.new(env)] : [] request_nonce = nonce_generator.call(*args) env[CONTENT_SECURITY_POLICY_NONCE_REQUEST_KEY] = request_nonce _, headers, _ = response = @app.call(env) headers["Content-Security-Policy"] = sub_nonce(headers["Content-Security-Policy"], request_nonce) response end private def nonce_generator Hanami.app.config.actions.content_security_policy_nonce_generator end def sub_nonce(string, nonce) string&.gsub("'nonce'", "'nonce-#{nonce}'") end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view.rb
lib/hanami/extensions/view.rb
# frozen_string_literal: true require "hanami/view" require_relative "view/slice_configured_view" module Hanami # @api private module Extensions # Integrated behavior for `Hanami::View` classes within Hanami apps. # # @see Hanami::View # # @api public # @since 2.1.0 module View # @api private # @since 2.1.0 def self.included(view_class) super view_class.extend(Hanami::SliceConfigurable) view_class.extend(ClassMethods) end # @api private # @since 2.1.0 module ClassMethods # @api private # @since 2.1.0 def configure_for_slice(slice) extend SliceConfiguredView.new(slice) end end end end end Hanami::View.include(Hanami::Extensions::View)
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/operation.rb
lib/hanami/extensions/operation.rb
# frozen_string_literal: true require "dry/operation" module Hanami module Extensions # Integrated behavior for `Dry::Operation` classes within Hanami apps. # # @see https://github.com/dry-rb/dry-operation # # @api public # @since 2.2.0 module Operation require_relative "operation/slice_configured_db_operation" # @api private def self.extended(operation_class) super operation_class.extend(Hanami::SliceConfigurable) end # private # @api private def configure_for_slice(slice) extend SliceConfiguredDBOperation.new(slice) if Hanami.bundled?("hanami-db") end end end end Dry::Operation.extend(Hanami::Extensions::Operation)
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/action.rb
lib/hanami/extensions/action.rb
# frozen_string_literal: true require "hanami/action" require_relative "action/slice_configured_action" module Hanami # @api private module Extensions # Integrated behavior for `Hanami::Action` classes within Hanami apps. # # @see InstanceMethods # @see https://github.com/hanami/controller # # @api public # @since 2.0.0 module Action # @api private def self.included(action_class) super action_class.extend(Hanami::SliceConfigurable) action_class.extend(ClassMethods) action_class.prepend(InstanceMethods) end # Class methods for app-integrated actions. # # @since 2.0.0 module ClassMethods # @api private def configure_for_slice(slice) extend SliceConfiguredAction.new(slice) end end # Instance methods for app-integrated actions. # # @since 2.0.0 module InstanceMethods # @api private attr_reader :view # @api private attr_reader :view_context_class # Returns the app or slice's {Hanami::Slice::RoutesHelper RoutesHelper} for use within # action instance methods. # # @return [Hanami::Slice::RoutesHelper] # # @api public # @since 2.0.0 attr_reader :routes # Returns the app or slice's `Dry::Monitor::Rack::Middleware` for use within # action instance methods. # # @return [Dry::Monitor::Rack::Middleware] # # @api public # @since 2.0.0 attr_reader :rack_monitor # @overload def initialize(routes: nil, **kwargs) # Returns a new `Hanami::Action` with app components injected as dependencies. # # These dependencies are injected automatically so that a call to `.new` (with no # arguments) returns a fully integrated action. # # @param routes [Hanami::Slice::RoutesHelper] # # @api public # @since 2.0.0 def initialize(view: nil, view_context_class: nil, rack_monitor: nil, routes: nil, **kwargs) @view = view @view_context_class = view_context_class @routes = routes @rack_monitor = rack_monitor super(**kwargs) end private # @api private def build_response(**options) options = options.merge(view_options: method(:view_options)) super(**options) end # @api private def finish(req, res, halted) res.render(view, **req.params) if !halted && auto_render?(res) super end # @api private def _handle_exception(request, _response, _exception) super rescue StandardError => exception rack_monitor&.instrument(:error, exception: exception, env: request.env) raise end # @api private def view_options(request, response) {context: view_context_class&.new(**view_context_options(request, response))}.compact end # @api private def view_context_options(request, response) # rubocop:disable Lint:UnusedMethodArgument {request: request} end # Returns true if a view should automatically be rendered onto the response body. # # This may be overridden to enable or disable automatic rendering. # # @param res [Hanami::Action::Response] # # @return [Boolean] # # @since 2.0.0 # @api public def auto_render?(res) view && res.body.empty? end end end end end Hanami::Action.include(Hanami::Extensions::Action)
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/db/repo.rb
lib/hanami/extensions/db/repo.rb
# frozen_string_literal: true require "hanami/db" module Hanami module Extensions # @api private # @since 2.2.0 module DB # @api private # @since 2.2.0 module Repo def self.included(repo_class) super repo_class.extend(Hanami::SliceConfigurable) repo_class.extend(ClassMethods) end # @api private # @since 2.2.0 module ClassMethods def configure_for_slice(slice) extend SliceConfiguredRepo.new(slice) end end end # @api private # @since 2.2.0 class SliceConfiguredRepo < Module attr_reader :slice def initialize(slice) super() @slice = slice end def extended(repo_class) define_inherited configure_repo(repo_class) define_new end def inspect "#<#{self.class.name}[#{slice.name}]>" end private def define_inherited root_for_repo_class = method(:root_for_repo_class) define_method(:inherited) do |subclass| super(subclass) unless subclass.root root = root_for_repo_class.(subclass) subclass.root root if root end end end def configure_repo(repo_class) repo_class.struct_namespace struct_namespace end def define_new resolve_rom = method(:resolve_rom) define_method(:new) do |**kwargs| container = kwargs.delete(:container) || resolve_rom.() super(container: container, **kwargs) end end def resolve_rom slice["db.rom"] end REPO_CLASS_NAME_REGEX = /^(?<name>.+)_(repo|repository)$/ def root_for_repo_class(repo_class) repo_class_name = slice.inflector.demodulize(repo_class) .then { slice.inflector.underscore(_1) } repo_class_match = repo_class_name.match(REPO_CLASS_NAME_REGEX) return unless repo_class_match repo_class_match[:name] .then { slice.inflector.pluralize(_1) } .then(&:to_sym) end def struct_namespace @struct_namespace ||= if slice.namespace.const_defined?(:Structs) slice.namespace.const_get(:Structs) else slice.namespace.const_set(:Structs, Module.new) end end end end end end Hanami::DB::Repo.include(Hanami::Extensions::DB::Repo)
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/action/slice_configured_action.rb
lib/hanami/extensions/action/slice_configured_action.rb
# frozen_string_literal: true module Hanami module Extensions module Action # Provides slice-specific configuration and behavior for any action class defined # within a slice's module namespace. # # @api private # @since 2.0.0 class SliceConfiguredAction < Module attr_reader :slice def initialize(slice) super() @slice = slice end def extended(action_class) configure_action(action_class) extend_behavior(action_class) define_new end def inspect "#<#{self.class.name}[#{slice.name}]>" end private # @see Hanami::Extensions::Action::InstanceMethods#initialize def define_new resolve_view = method(:resolve_paired_view) view_context_class = method(:view_context_class) resolve_routes = method(:resolve_routes) resolve_rack_monitor = method(:resolve_rack_monitor) define_method(:new) do |**kwargs| super( view: kwargs.fetch(:view) { resolve_view.(self) }, view_context_class: kwargs.fetch(:view_context_class) { view_context_class.() }, routes: kwargs.fetch(:routes) { resolve_routes.() }, rack_monitor: kwargs.fetch(:rack_monitor) { resolve_rack_monitor.() }, **kwargs, ) end end def configure_action(action_class) action_class.settings.each do |setting| # Configure the action from config on the slice, _unless it has already been configured # by a parent slice_, and re-configuring it for this slice would make no change. # # In the case of most slices, its actions config is likely to be the same as its parent # (since each slice copies its `config` from its parent), and if we re-apply the config # here, then it may possibly overwrite config customisations explicitly made in parent # action classes. # # For example, given an app-level base action class, with custom config: # # module MyApp # class Action < Hanami::Action # config.format :json # end # end # # And then an action in a slice inheriting from it: # # module MySlice # module Actions # class SomeAction < MyApp::Action # end # end # end # # In this case, `SliceConfiguredAction` will be extended two times: # # 1. When `MyApp::Action` is defined # 2. Again when `MySlice::Actions::SomeAction` is defined # # If we blindly re-configure all action settings each time `SliceConfiguredAction` is # extended, then at the point of (2) above, we'd end up overwriting the custom # `config.default_response_format` explicitly configured in the `MyApp::Action` base # class, leaving `MySlice::Actions::SomeAction` with `config.default_response_format` of # `:html` (the default at `Hanami.app.config.actions.default_response_format`), and not # the `:json` value configured in its immediate superclass. # # This would be surprising behavior, and we want to avoid it. slice_value = slice.config.actions.public_send(setting.name) parent_value = slice.parent.config.actions.public_send(setting.name) if slice.parent next if slice.parent && slice_value == parent_value action_class.config.public_send( :"#{setting.name}=", setting.mutable? ? slice_value.dup : slice_value ) end end def extend_behavior(action_class) if actions_config.sessions.enabled? require "hanami/action/session" action_class.include Hanami::Action::Session end if actions_config.csrf_protection require "hanami/action/csrf_protection" action_class.include Hanami::Action::CSRFProtection end if actions_config.cookies.enabled? require "hanami/action/cookies" action_class.include Hanami::Action::Cookies end end def resolve_paired_view(action_class) view_identifiers = actions_config.view_name_inferrer.call( action_class_name: action_class.name, slice: slice, ) view_identifiers.each do |identifier| return slice[identifier] if slice.key?(identifier) end nil end def view_context_class if Hanami.bundled?("hanami-view") return Extensions::View::Context.context_class(slice) end # If hanami-view isn't bundled, try and find a possible third party context class with the # same `Views::Context` name (but don't fall back to automatically defining one). if slice.namespace.const_defined?(:Views) views_namespace = slice.namespace.const_get(:Views) if views_namespace.const_defined?(:Context) views_namespace.const_get(:Context) end end end def resolve_routes slice.app["routes"] if slice.app.key?("routes") end def resolve_rack_monitor slice.app["rack.monitor"] if slice.app.key?("rack.monitor") end def actions_config slice.config.actions end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/operation/slice_configured_db_operation.rb
lib/hanami/extensions/operation/slice_configured_db_operation.rb
# frozen_string_literal: true module Hanami module Extensions module Operation # Extends operations to support the database. # # Add an initializer accepting a `rom:` dependency, which is supplied automatically from the # `"db.rom"` component in the operation's slice. # # @api private class SliceConfiguredDBOperation < Module attr_reader :slice def initialize(slice) super() @slice = slice end def extended(operation_class) require "dry/operation/extensions/rom" operation_class.include Dry::Operation::Extensions::ROM operation_class.include InstanceMethods operation_class.include SliceInstanceMethods.new(slice) define_new end def inspect "#<#{self.class.name}[#{slice.name}>" end private def define_new resolve_rom = method(:resolve_rom) define_method(:new) do |**kwargs| super( **kwargs, rom: kwargs.fetch(:rom) { resolve_rom.() }, ) end end def resolve_rom slice["db.rom"] if slice.key?("db.rom") end module InstanceMethods attr_reader :rom def initialize(rom:, **) @rom = rom end end class SliceInstanceMethods < Module attr_reader :slice def initialize(slice) @slice = slice end def included(operation_class) define_transaction end private def define_transaction slice = self.slice define_method(:transaction) do |**kwargs, &block| unless rom msg = <<~TEXT.strip A configured db for #{slice} is required to run transactions. TEXT raise Hanami::ComponentLoadError, msg end super(**kwargs, &block) end end end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/standard_helpers.rb
lib/hanami/extensions/view/standard_helpers.rb
# frozen_string_literal: true module Hanami module Extensions module View # Module including the standard library of Hanami helpers # # @api public # @since 2.1.0 module StandardHelpers include Hanami::View::Helpers::EscapeHelper include Hanami::View::Helpers::NumberFormattingHelper include Hanami::View::Helpers::TagHelper include Helpers::FormHelper if Hanami.bundled?("hanami-assets") include Helpers::AssetsHelper end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/slice_configured_view.rb
lib/hanami/extensions/view/slice_configured_view.rb
# frozen_string_literal: true module Hanami module Extensions module View # Provides slice-specific configuration and behavior for any view class defined within a # slice's module namespace. # # @api public # @since 2.1.0 class SliceConfiguredView < Module TEMPLATES_DIR = "templates" VIEWS_DIR = "views" PARTS_DIR = "parts" SCOPES_DIR = "scopes" attr_reader :slice # @api private # @since 2.1.0 def initialize(slice) super() @slice = slice end # @api private # @since 2.1.0 def extended(view_class) load_app_view configure_view(view_class) define_inherited end # @return [String] # # @api public # @since 2.1.0 def inspect "#<#{self.class.name}[#{slice.name}]>" end private # If the given view doesn't inherit from the app view, attempt to load it anyway, since # requiring the app view is necessary for _its_ `SliceConfiguredView` hook to execute and # define the app-level part and scope classes that we refer to here. def load_app_view return if app? begin slice.app.namespace.const_get(:View, false) rescue NameError => e raise unless e.name == :View end end # rubocop:disable Metrics/AbcSize def configure_view(view_class) view_class.settings.each do |setting| next unless slice.config.views.respond_to?(setting.name) # Configure the view from config on the slice, _unless it has already been configured by # a parent slice_, and re-configuring it for this slice would make no change. # # In the case of most slices, its views config is likely to be the same as its parent # (since each slice copies its `config` from its parent), and if we re-apply the config # here, then it may possibly overwrite config customisations explicitly made in parent # view classes. # # For example, given an app-level base view class, with custom config: # # module MyApp # class View < Hanami::View # config.layout = "custom_layout" # end # end # # And then a view in a slice inheriting from it: # # module MySlice # module Views # class SomeView < MyApp::View # end # end # end # # In this case, `SliceConfiguredView` will be extended two times: # # 1. When `MyApp::View` is defined # 2. Again when `MySlice::Views::SomeView` is defined # # If we blindly re-configure all view settings each time `SliceConfiguredView` is # extended, then at the point of (2) above, we'd end up overwriting the custom # `config.layout` explicitly configured in the `MyApp::View` base class, leaving # `MySlice::Views::SomeView` with `config.layout` of `"app"` (the default as specified # at `Hanami.app.config.views.layout`), and not the `"custom_layout"` value configured # in its immediate superclass. # # This would be surprising behavior, and we want to avoid it. slice_value = slice.config.views.public_send(setting.name) parent_value = slice.parent.config.views.public_send(setting.name) if slice.parent next if slice.parent && slice_value == parent_value view_class.config.public_send( :"#{setting.name}=", setting.mutable? ? slice_value.dup : slice_value ) end view_class.config.inflector = inflector # Configure the paths for this view if: # - We are the app, and a user hasn't provided custom `paths` (in this case, we need to # set the defaults) # - We are a slice, and the view's inherited `paths` is identical to the parent's config # (which would result in the view in a slice erroneously trying to find templates in # the app) if view_class.config.paths.empty? || (slice.parent && view_class.config.paths.map(&:dir) == [templates_path(slice.parent)]) view_class.config.paths = templates_path(slice) end view_class.config.template = template_name(view_class) view_class.config.default_context = Extensions::View::Context.context_class(slice).new view_class.config.part_class = part_class view_class.config.scope_class = scope_class if (part_namespace = namespace_from_path("#{VIEWS_DIR}/#{PARTS_DIR}")) view_class.config.part_namespace = part_namespace end if (scope_namespace = namespace_from_path("#{VIEWS_DIR}/#{SCOPES_DIR}")) view_class.config.scope_namespace = scope_namespace end end # rubocop:enable Metrics/AbcSize def define_inherited template_name = method(:template_name) define_method(:inherited) do |subclass| super(subclass) subclass.config.template = template_name.(subclass) end end def templates_path(slice) if slice.app.equal?(slice) slice.root.join(APP_DIR, TEMPLATES_DIR) else slice.root.join(TEMPLATES_DIR) end end def namespace_from_path(path) path = "#{slice.slice_name.path}/#{path}" begin require path rescue LoadError => exception raise exception unless exception.path == path end begin inflector.constantize(inflector.camelize(path)) rescue NameError # rubocop: disable Lint/SuppressedException end end def template_name(view_class) inflector .underscore(view_class.name) .sub(/^#{slice.slice_name.path}\//, "") .sub(/^#{VIEWS_DIR}\//, "") end def inflector slice.inflector end def part_class @part_class ||= if views_namespace.const_defined?(:Part) views_namespace.const_get(:Part) else views_namespace.const_set(:Part, Class.new(part_superclass).tap { |klass| # Give the slice to `configure_for_slice`, since it cannot be inferred when it is # called via `.inherited`, because the class is anonymous at this point klass.configure_for_slice(slice) }) end end def part_superclass return Hanami::View::Part if app? begin inflector.constantize(inflector.camelize("#{slice.app.slice_name.name}/views/part")) rescue NameError Hanami::View::Part end end def scope_class @scope_class ||= if views_namespace.const_defined?(:Scope) views_namespace.const_get(:Scope) else views_namespace.const_set(:Scope, Class.new(scope_superclass).tap { |klass| # Give the slice to `configure_for_slice`, since it cannot be inferred when it is # called via `.inherited`, since the class is anonymous at this point klass.configure_for_slice(slice) }) end end def scope_superclass return Hanami::View::Scope if app? begin inflector.constantize(inflector.camelize("#{slice.app.slice_name.name}/views/scope")) rescue NameError Hanami::View::Scope end end def views_namespace @slice_views_namespace ||= if slice.namespace.const_defined?(:Views) slice.namespace.const_get(:Views) else slice.namespace.const_set(:Views, Module.new) end end def app? slice.app == slice end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/scope.rb
lib/hanami/extensions/view/scope.rb
# frozen_string_literal: true require_relative "slice_configured_helpers" require_relative "standard_helpers" module Hanami module Extensions module View # @api private # @since 2.1.0 module Scope # @api private # @since 2.1.0 def self.included(scope_class) super scope_class.extend(Hanami::SliceConfigurable) scope_class.include(StandardHelpers) scope_class.extend(ClassMethods) end # @api private # @since 2.1.0 module ClassMethods # @api private # @since 2.1.0 def configure_for_slice(slice) extend SliceConfiguredHelpers.new(slice) end end end end end end Hanami::View::Scope.include(Hanami::Extensions::View::Scope)
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/slice_configured_part.rb
lib/hanami/extensions/view/slice_configured_part.rb
# frozen_string_literal: true module Hanami module Extensions module View # Provides slice-specific configuration and behavior for any view part class defined within a # slice's module namespace. # # @api public # @since 2.1.0 class SliceConfiguredPart < Module attr_reader :slice # @api private # @since 2.1.0 def initialize(slice) super() @slice = slice end # @api private # @since 2.1.0 def extended(klass) define_new end # @return [String] # # @api public # @since 2.1.0 def inspect "#<#{self.class.name}[#{slice.name}]>" end private # Defines a `.new` method on the part class that provides a default `rendering:` argument of # a rendering coming from a view configured for the slice. This means that any part can be # initialized standalone (with a `value:` only) and still have access to all the integrated # view facilities from the slice, such as helpers. This is helpful when unit testing parts. # # @example # module MyApp::Views::Parts # class Post < MyApp::View::Part # def title_tag # helpers.h1(value.title) # end # end # end # # # Useful when unit testing parts # part = MyApp::Views::Parts::Post.new(value: hello_world_post) # part.title_tag # => "<h1>Hello world</h1>" def define_new slice = self.slice define_method(:new) do |**args| return super(**args) if args.key?(:rendering) slice_rendering = Class.new(Hanami::View) .configure_for_slice(slice) .new .rendering super(rendering: slice_rendering, **args) end end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/context.rb
lib/hanami/extensions/view/context.rb
# frozen_string_literal: true require_relative "../../errors" require_relative "slice_configured_context" module Hanami module Extensions module View # View context for views in Hanami apps. # # @api public # @since 2.1.0 module Context class << self # Returns a context class for the given slice. If a context class is not defined, defines # a class named `Views::Context` within the slice's namespace. # # @api private # @since 2.1.0 def context_class(slice) views_namespace = views_namespace(slice) if views_namespace.const_defined?(:Context) return views_namespace.const_get(:Context) end views_namespace.const_set(:Context, Class.new(context_superclass(slice)).tap { |klass| klass.configure_for_slice(slice) }) end private # @api private # @since 2.1.0 def context_superclass(slice) return Hanami::View::Context if Hanami.app.equal?(slice) begin slice.inflector.constantize( slice.inflector.camelize("#{slice.app.slice_name.name}/views/context") ) rescue NameError => e raise e unless %i[Views Context].include?(e.name) Hanami::View::Context end end # @api private # @since 2.1.0 def views_namespace(slice) # TODO: this could be moved into the top-level Extensions::View if slice.namespace.const_defined?(:Views) slice.namespace.const_get(:Views) else slice.namespace.const_set(:Views, Module.new) end end end # @api private # @since 2.1.0 module ClassExtension def self.included(context_class) super context_class.extend(Hanami::SliceConfigurable) context_class.extend(ClassMethods) context_class.prepend(InstanceMethods) end # @api private # @since 2.1.0 module ClassMethods # @api private # @since 2.1.0 def configure_for_slice(slice) extend SliceConfiguredContext.new(slice) end end # @api public # @since 2.1.0 module InstanceMethods # Returns the app's inflector. # # @return [Dry::Inflector] the inflector # # @api public # @since 2.1.0 attr_reader :inflector # @see SliceConfiguredContext#define_new # # @api private # @since 2.1.0 def initialize( # rubocop:disable Metrics/ParameterLists inflector: nil, routes: nil, assets: nil, request: nil, **args ) @inflector = inflector @routes = routes @assets = assets @request = request @content_for = {} super(**args) end # @api private # @since 2.1.0 def initialize_copy(source) # The standard implementation of initialize_copy will make shallow copies of all # instance variables from the source. This is fine for most of our ivars. super # Dup any objects that will be mutated over a given rendering to ensure no leakage of # state across distinct view renderings. @content_for = source.instance_variable_get(:@content_for).dup end # Returns the app's assets. # # @return [Hanami::Assets] the assets # # @raise [Hanami::ComponentLoadError] if the hanami-assets gem is not bundled # # @api public # @since 2.1.0 def assets unless @assets msg = if Hanami.bundled?("hanami-assets") "Have you put files into your assets directory?" else "The hanami-assets gem is required to access assets." end raise Hanami::ComponentLoadError, "Assets not available. #{msg}" end @assets end # Returns the current request, if the view is rendered from within an action. # # @return [Hanami::Action::Request] the request # # @raise [Hanami::ComponentLoadError] if the view is not rendered from within a request # # @api public # @since 2.1.0 def request unless @request raise Hanami::ComponentLoadError, "Request not available. Only views rendered from Hanami::Action instances have a request." end @request end # Returns true if the view is rendered from within an action and a request is available. # # @return [Boolean] # # @api public # @since 2.3.0 def request? !!@request end # Returns the app's routes helper. # # @return [Hanami::Slice::RoutesHelper] the routes helper # # @raise [Hanami::ComponentLoadError] if the hanami-router gem is not bundled or routes # are not defined # # @api public # @since 2.1.0 def routes unless @routes raise Hanami::ComponentLoadError, "the hanami-router gem is required to access routes" end @routes end # @overload content_for(key, value = nil, &block) # Stores a string or block of template markup for later use. # # @param key [Symbol] the content key, for later retrieval # @param value [String, nil] the content, if no block is given # # @return [String] the content # # @example # content_for(:page_title, "Hello world") # # @example In a template # <%= content_for :page_title do %> # <h1>Hello world</h1> # <% end %> # # @overload content_for(key) # Returns the previously stored content for the given key. # # @param key [Symbol] the content key # # @return [String, nil] the content, or nil if no content previously stored with the # key # # @api public # @since 2.1.0 def content_for(key, value = nil) if block_given? @content_for[key] = yield nil elsif value @content_for[key] = value nil else @content_for[key] end end # Returns the current request's CSRF token. # # @return [String] the token # # @raise [Hanami::ComponentLoadError] if the view is not rendered from within a request # @raise [Hanami::Action::MissingSessionError] if sessions are not enabled # # @api public # @since 2.1.0 def csrf_token request.session[Hanami::Action::CSRFProtection::CSRF_TOKEN] end # Returns the session for the current request. # # @return [Rack::Session::Abstract::SessionHash] the session hash # # @raise [Hanami::ComponentLoadError] if the view is not rendered from within a request # @raise [Hanami::Action::MissingSessionError] if sessions are not enabled # # @api public # @since 2.1.0 def session request.session end # Returns the flash hash for the current request. # # @return [] # # @raise [Hanami::ComponentLoadError] if the view is not rendered from within a request # @raise [Hanami::Action::MissingSessionError] if sessions are not enabled # # @api public # @since 2.1.0 def flash request.flash end end end end end end end Hanami::View::Context.include(Hanami::Extensions::View::Context::ClassExtension)
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/slice_configured_helpers.rb
lib/hanami/extensions/view/slice_configured_helpers.rb
# frozen_string_literal: true module Hanami module Extensions module View # Provides slice-specific helper methods for any view object requiring access to helpers. # # @api public # @since 2.1.0 class SliceConfiguredHelpers < Module attr_reader :slice # @api private # @since 2.1.0 def initialize(slice) super() @slice = slice end # @api private # @since 2.1.0 def extended(klass) include_helpers(klass) end # @return [String] # # @api public # @since 2.1.0 def inspect "#<#{self.class.name}[#{slice.name}]>" end private def include_helpers(klass) if mod = helpers_module(slice.app) klass.include(mod) end if mod = helpers_module(slice) klass.include(mod) end end def helpers_module(slice) return unless slice.namespace.const_defined?(:Views) return unless slice.namespace.const_get(:Views).const_defined?(:Helpers) slice.namespace.const_get(:Views).const_get(:Helpers) end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/slice_configured_context.rb
lib/hanami/extensions/view/slice_configured_context.rb
# frozen_string_literal: true module Hanami module Extensions module View # Provides slice-specific configuration and behavior for any view context class defined within # a slice's module namespace. # # @api public # @since 2.1.0 class SliceConfiguredContext < Module attr_reader :slice # @api private # @since 2.1.0 def initialize(slice) super() @slice = slice end # @api private # @since 2.1.0 def extended(_context_class) define_new end # @api public # @since 2.1.0 def inspect "#<#{self.class.name}[#{slice.name}]>" end private # Defines a {.new} method on the context class that resolves key components from the app # container and provides them to {#initialize} as injected dependencies. # # This includes the following app components: # - the configured inflector as `inflector` # - "routes" from the app container as `routes` # - "assets" from the app container as `assets` def define_new inflector = slice.inflector resolve_routes = method(:resolve_routes) resolve_assets = method(:resolve_assets) define_method :new do |**kwargs| kwargs[:inflector] ||= inflector kwargs[:routes] ||= resolve_routes.() kwargs[:assets] ||= resolve_assets.() super(**kwargs) end end def resolve_routes slice["routes"] if slice.key?("routes") end def resolve_assets slice["assets"] if slice.key?("assets") end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/view/part.rb
lib/hanami/extensions/view/part.rb
# frozen_string_literal: true require_relative "standard_helpers" require_relative "slice_configured_part" module Hanami module Extensions module View # @api public # @since 2.1.0 module Part # @api private # @since 2.1.0 def self.included(part_class) super part_class.extend(Hanami::SliceConfigurable) part_class.extend(ClassMethods) end # @api private # @since 2.1.0 module ClassMethods # @api private # @since 2.1.0 def configure_for_slice(slice) extend SliceConfiguredPart.new(slice) const_set :PartHelpers, Class.new(PartHelpers) { |klass| klass.configure_for_slice(slice) } end end # Returns an object including the default Hanami helpers as well as the user-defined helpers # for the part's slice. # # Use this when you need to access helpers inside your part classes. # # @return [Object] the helpers object # # @api public # @since 2.1.0 def helpers @helpers ||= self.class.const_get(:PartHelpers).new(context: _context) end end # Standalone helpers class including both {StandardHelpers} as well as the user-defined # helpers for the slice. # # Used where helpers should be addressed via an intermediary object (i.e. in parts), # rather than mixed into a class directly. # # @api private # @since 2.1.0 class PartHelpers extend Hanami::SliceConfigurable include StandardHelpers # @api private # @since 2.1.0 def self.configure_for_slice(slice) extend SliceConfiguredHelpers.new(slice) end # Returns the context for the current view rendering. # # @return [Hanami::View::Context] the context # # @api public # @since 2.1.0 attr_reader :_context # @api public # @since 2.1.0 alias_method :context, :_context # @api private # @since 2.1.0 def initialize(context:) @_context = context end end end end end Hanami::View::Part.include(Hanami::Extensions::View::Part)
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/extensions/router/errors.rb
lib/hanami/extensions/router/errors.rb
# frozen_string_literal: true require "hanami/router" module Hanami class Router # Error raised when a request is made for a missing route. # # Raised only when using hanami-router as part of a full Hanami app. When using hanami-router # standalone, the behavior for such requests is to return a "Not Found" response. # # @api public # @since 2.1.0 class NotFoundError < Hanami::Router::Error # @return [Hash] the Rack environment for the request # # @api public # @since 2.1.0 attr_reader :env def initialize(env) @env = env message = "No route found for #{env["REQUEST_METHOD"]} #{env["PATH_INFO"]}" super(message) end end # Error raised when a request is made for a route using a HTTP method not allowed on the route. # # Raised only when using hanami-router as part of a full Hanami app. When using hanami-router # standalone, the behavior for such requests is to return a "Method Not Allowed" response. # # @api public # @since 2.1.0 class NotAllowedError < Hanami::Router::Error # @return [Hash] the Rack environment for the request # # @api public # @since 2.1.0 attr_reader :env # @return [Array<String>] the allowed methods for the route # # @api public # @since 2.1.0 attr_reader :allowed_methods def initialize(env, allowed_methods) @env = env @allowed_methods = allowed_methods message = "Only #{allowed_methods.join(', ')} requests are allowed at #{env["PATH_INFO"]}" super(message) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/logger.rb
lib/hanami/providers/logger.rb
# frozen_string_literal: true module Hanami # @api private module Providers # Provider source to register logger component in Hanami slices. # # @see Hanami::Config#logger # # @api private # @since 2.0.0 class Logger < Hanami::Provider::Source # @api private def start register :logger, Hanami.app.config.logger_instance end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/db.rb
lib/hanami/providers/db.rb
# frozen_string_literal: true require "dry/configurable" require "dry/core" require "uri" require_relative "../constants" module Hanami module Providers # @api private # @since 2.2.0 class DB < Hanami::Provider::Source extend Dry::Core::Cache include Dry::Configurable(config_class: Providers::DB::Config) setting :adapters, mutable: true, default: Adapters.new setting :gateways, default: {} def initialize(...) super(...) @config_finalized = false end def finalize_config return if @config_finalized apply_parent_config if apply_parent_config? configure_gateways @config_finalized = true self end def prepare prepare_and_import_parent_db and return if import_from_parent? override_rom_inflector finalize_config require "hanami-db" gateways = prepare_gateways if gateways[:default] register "gateway", gateways[:default] elsif gateways.length == 1 register "gateway", gateways.values.first end gateways.each do |key, gateway| register "gateways.#{key}", gateway end @rom_config = ROM::Configuration.new(gateways) config.each_plugin do |adapter_name, plugin_spec, config_block| if config_block @rom_config.plugin(adapter_name, plugin_spec) do |plugin_config| instance_exec(plugin_config, &config_block) end else @rom_config.plugin(adapter_name, plugin_spec) end end register "config", @rom_config end def start start_and_import_parent_db and return if import_from_parent? # Set up DB logging for the whole app. We share the app's notifications bus across all # slices, so we only need to configure the subsciprtion for DB logging just once. slice.app.start :db_logging # Register ROM components register_rom_components :relation, "relations" register_rom_components :command, File.join("db", "commands") register_rom_components :mapper, File.join("db", "mappers") rom = ROM.container(@rom_config) register "rom", rom end def stop slice["db.rom"].disconnect end # @api private # @since 2.2.0 def database_urls finalize_config config.gateways.transform_values { _1.database_url } end private def parent_db_provider return @parent_db_provider if instance_variable_defined?(:@parent_db_provider) @parent_db_provider = slice.parent && slice.parent.container.providers[:db] end def apply_parent_config parent_db_provider.source.finalize_config self.class.settings.keys.each do |key| # Preserve settings already configured locally next if config.configured?(key) # Skip gateway config, we handle this in #configure_gateways next if key == :gateways # Skip adapter config, we handle this below next if key == :adapters config[key] = parent_db_provider.source.config[key] end parent_db_provider.source.config.adapters.each do |adapter_name, parent_adapter| adapter = config.adapter(adapter_name) adapter.class.settings.keys.each do |key| next if adapter.config.configured?(key) adapter.config[key] = parent_adapter.config[key].dup end end end def apply_parent_config? slice.config.db.configure_from_parent && parent_db_provider end def import_from_parent? slice.config.db.import_from_parent && slice.parent end def prepare_and_import_parent_db return unless parent_db_provider slice.parent.prepare :db @rom_config = slice.parent["db.config"] register "config", (@rom_config = slice.parent["db.config"]) register "gateway", slice.parent["db.gateway"] end def start_and_import_parent_db return unless parent_db_provider slice.parent.start :db register "rom", slice.parent["db.rom"] end # ROM 5.3 doesn't have a configurable inflector. # # This is a problem in Hanami because using different # inflection rules for ROM will lead to constant loading # errors. def override_rom_inflector return if ROM::Inflector == Hanami.app["inflector"] ROM.instance_eval { remove_const :Inflector const_set :Inflector, Hanami.app["inflector"] } end def configure_gateways # Create gateway configs for gateways detected from database_url ENV vars database_urls_from_env = detect_database_urls_from_env database_urls_from_env.keys.each do |key| config.gateways[key] ||= Gateway.new end # Create a single default gateway if none is configured or detected from database URLs config.gateways[:default] = Gateway.new if config.gateways.empty? # Leave gateways in a stable order: :default first, followed by others in sort order if config.gateways.length > 1 gateways = config.gateways config.gateways = {default: gateways[:default], **gateways.sort.to_h}.compact end config.gateways.each do |key, gw_config| gw_config.database_url ||= database_urls_from_env.fetch(key) { raise Hanami::ComponentLoadError, "A database_url for gateway #{key} is required to start :db." } ensure_database_gem(gw_config.database_url) apply_parent_gateway_config(key, gw_config) if apply_parent_config? gw_config.configure_adapter(config.adapters) end end def apply_parent_gateway_config(key, gw_config) parent_gw_config = parent_db_provider.source.config.gateways[key] # Only copy config from a parent gateway with the same name _and_ database URL return unless parent_gw_config&.database_url == gw_config.database_url # Copy config from matching parent gateway (gw_config.class.settings.keys - [:adapter]).each do |key| next if gw_config.config.configured?(key) gw_config.config[key] = parent_gw_config.config[key].dup end # If there is an adapter configured within this slice, prefer that, and do not copy the # adapter from the parent gateway unless config.adapters[gw_config.adapter_name] || gw_config.configured?(:adapter) gw_config.adapter = parent_gw_config.adapter.dup end end def prepare_gateways config.gateways.transform_values { |gw_config| # Avoid spurious connections by reusing identically configured gateways across slices fetch_or_store(gw_config.cache_keys) { ROM::Gateway.setup( gw_config.adapter_name, gw_config.database_url, **gw_config.options ) } } end def detect_database_urls_from_env database_urls = {} env_var_prefix = slice.slice_name.name.gsub("/", "__").upcase + "__" unless slice.app? # Build gateway URLs from ENV vars with specific gateway named suffixes gateway_prefix = "#{env_var_prefix}DATABASE_URL__" ENV.select { |(k, _)| k.start_with?(gateway_prefix) } .each do |(var, _)| gateway_name = var.split(gateway_prefix).last.downcase database_urls[gateway_name.to_sym] = ENV[var] end # Set the default gateway from ENV var without suffix if !database_urls.key?(:default) fallback_vars = ["#{env_var_prefix}DATABASE_URL", "DATABASE_URL"].uniq fallback_vars.each do |var| url = ENV[var] database_urls[:default] = url and break if url end end if Hanami.env?(:test) database_urls.transform_values! { Hanami::DB::Testing.database_url(_1) } end database_urls end # @api private # @since 2.2.0 DATABASE_GEMS = { "mysql2" => "mysql2", "postgres" => "pg", "sqlite" => "sqlite3" }.freeze private_constant :DATABASE_GEMS # Raises an error if the relevant database gem for the configured database_url is not # installed. # # Takes a conservative approach to raising errors. It only does so for the database_url # schemes generated by the `hanami new` CLI command. Uknown schemes are ignored and no errors # are raised. def ensure_database_gem(database_url) scheme = URI(database_url).scheme return unless scheme database_gem = DATABASE_GEMS[scheme] return unless database_gem return if Hanami.bundled?(database_gem) raise Hanami::ComponentLoadError, %(The "#{database_gem}" gem is required to connect to #{database_url}. Please add it to your Gemfile.) end def register_rom_components(component_type, path) components_path = target.source_path.join(path) components_path.glob("**/*.rb").each do |component_file| component_name = component_file .relative_path_from(components_path) .sub(RB_EXT_REGEXP, "") .to_s component_class = target.inflector.camelize( "#{target.slice_name.name}/#{path}/#{component_name}" ).then { target.inflector.constantize(_1) } @rom_config.public_send(:"register_#{component_type}", component_class) end end end Dry::System.register_provider_source( :db, source: DB, group: :hanami, provider_options: {namespace: true} ) end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/inflector.rb
lib/hanami/providers/inflector.rb
# frozen_string_literal: true module Hanami # @api private module Providers # Provider source to register inflector component in Hanami slices. # # @api private # @since 2.0.0 class Inflector < Hanami::Provider::Source # @api private def start register :inflector, Hanami.app.inflector end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/rack.rb
lib/hanami/providers/rack.rb
# frozen_string_literal: true module Hanami # @api private module Providers # Provider source to register Rack integration components in Hanami slices. # # @see Hanami::Providers::Logger # @see Hanami::Web::RackLogger # @see https://github.com/rack/rack # @see https://dry-rb.org/gems/dry-monitor/ # # @api private # @since 2.0.0 class Rack < Hanami::Provider::Source # @api private def prepare Dry::Monitor.load_extensions(:rack) # Explicitly register the Rack middleware events on our notifications bus. The Dry::Monitor # rack extension (activated above) does register these globally, but if the notifications # bus has been used before this provider loads, then it will have created its own separate # local copy of all registered events as of that moment in time, which will not be included # in the Rack events globally registered above. notifications = target["notifications"] notifications.register_event(Dry::Monitor::Rack::Middleware::REQUEST_START) notifications.register_event(Dry::Monitor::Rack::Middleware::REQUEST_STOP) notifications.register_event(Dry::Monitor::Rack::Middleware::REQUEST_ERROR) end # @api private def start slice.start :logger monitor_middleware = Dry::Monitor::Rack::Middleware.new( target["notifications"], clock: Dry::Monitor::Clock.new(unit: :microsecond) ) rack_logger = Hanami::Web::RackLogger.new(target[:logger], env: slice.container.env) rack_logger.attach(monitor_middleware) register "monitor", monitor_middleware end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/routes.rb
lib/hanami/providers/routes.rb
# frozen_string_literal: true module Hanami # @api private module Providers # Provider source to register routes helper component in Hanami slices. # # @see Hanami::Slice::RoutesHelper # # @api private # @since 2.0.0 class Routes < Hanami::Provider::Source # @api private def prepare require "hanami/slice/routes_helper" end # @api private def start # Register a lazy instance of RoutesHelper to ensure we don't load prematurely load the # router during the process of booting. This ensures the router's resolver can run strict # action key checks once when it runs on a fully booted slice. register :routes do Hanami::Slice::RoutesHelper.new(slice.router) end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/relations.rb
lib/hanami/providers/relations.rb
# frozen_string_literal: true module Hanami module Providers # @api private # @since 2.2.0 class Relations < Hanami::Provider::Source def start start_and_import_parent_relations and return if slice.parent && slice.config.db.import_from_parent slice.start :db register_relations target["db.rom"] end private def register_relations(rom) rom.relations.each do |name, _| register name, rom.relations[name] end end def start_and_import_parent_relations slice.parent.start :relations register_relations slice.parent["db.rom"] end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/db_logging.rb
lib/hanami/providers/db_logging.rb
# frozen_string_literal: true module Hanami module Providers # @api private # @since 2.2.0 class DBLogging < Hanami::Provider::Source # @api private # @since 2.2.0 def prepare require "dry/monitor/sql/logger" slice["notifications"].register_event :sql end # @api private # @since 2.2.0 def start Dry::Monitor::SQL::Logger.new(slice["logger"]).subscribe(slice["notifications"]) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/assets.rb
lib/hanami/providers/assets.rb
# frozen_string_literal: true module Hanami # @api private module Providers # Provider source to register routes helper component in Hanami slices. # # @see Hanami::Slice::RoutesHelper # # @api private # @since 2.0.0 class Assets < Hanami::Provider::Source # @api private def prepare require "hanami/assets" end # @api private def start root = slice.app.root.join("public", "assets", Hanami::Assets.public_assets_dir(target).to_s) assets = Hanami::Assets.new(config: slice.config.assets, root: root) register(:assets, assets) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/db/gateway.rb
lib/hanami/providers/db/gateway.rb
# frozen_string_literal: true require "dry/configurable" require "dry/core" module Hanami module Providers class DB < Hanami::Provider::Source # @api public # @since 2.2.0 class Gateway include Dry::Core::Constants include Dry::Configurable setting :database_url setting :adapter_name, default: :sql setting :adapter, mutable: true setting :connection_options, default: {} # @api public # @since 2.2.0 def adapter(name = Undefined) return config.adapter if name.eql?(Undefined) if block_given? # If a block is given, explicitly configure the gateway's adapter config.adapter_name = name adapter = (config.adapter ||= Adapters.new_adapter(name)) yield adapter adapter else # If an adapter name is given without a block, use the default adapter configured with # the same name config.adapter_name = adapter_name end end # @api public # @since 2.2.0 def connection_options(**options) if options.any? config.connection_options.merge!(options) end config.connection_options end # @api public # @since 2.2.0 def options {**connection_options, **config.adapter.gateway_options} end # @api private def configure_adapter(default_adapters) default_adapter = default_adapters.find(config.adapter_name) config.adapter ||= default_adapter.dup config.adapter.configure_from_adapter(default_adapter) config.adapter.configure_for_database(config.database_url) self end # @api private def cache_keys [config.database_url, config.connection_options, config.adapter.gateway_cache_keys] end private def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || super end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/db/adapter.rb
lib/hanami/providers/db/adapter.rb
# frozen_string_literal: true require "dry/configurable" module Hanami module Providers class DB < Hanami::Provider::Source # @api public # @since 2.2.0 class Adapter include Dry::Configurable # @api public # @since 2.2.0 setting :plugins, mutable: true # @api private def initialize(...) @skip_defaults = Hash.new(false) end # @api public # @since 2.2.0 def skip_defaults(setting_name = nil) @skip_defaults[setting_name] = true end # @api private private def skip_defaults?(setting_name = nil) @skip_defaults[setting_name] end # @api private def configure_from_adapter(other_adapter) return if skip_defaults? plugins.concat(other_adapter.plugins).uniq! unless skip_defaults?(:plugins) end # @api private def configure_for_database(database_url) end # @api public # @since 2.2.0 def plugin(**plugin_spec, &config_block) plugins << [plugin_spec, config_block] end # @api public # @since 2.2.0 def plugins config.plugins ||= [] end # @api private def gateway_cache_keys gateway_options end # @api private def gateway_options {} end # @api public # @since 2.2.0 def clear config.plugins = nil self end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/db/config.rb
lib/hanami/providers/db/config.rb
# frozen_string_literal: true require "dry/core" module Hanami module Providers class DB < Hanami::Provider::Source # @api public # @since 2.2.0 class Config < Dry::Configurable::Config include Dry::Core::Constants # @api public # @since 2.2.0 def gateway(key) gateway = (gateways[key] ||= Gateway.new) yield gateway if block_given? gateway end # @api public # @since 2.2.0 def adapter(name) adapter = adapters.adapter(name) yield adapter if block_given? adapter end # @api private def each_plugin return to_enum(__method__) unless block_given? gateways.values.group_by(&:adapter_name).each do |adapter_name, adapter_gateways| per_adapter_plugins = adapter_gateways.map { _1.adapter.plugins }.flatten(1).uniq per_adapter_plugins.each do |plugin_spec, config_block| yield adapter_name, plugin_spec, config_block end end end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/db/adapters.rb
lib/hanami/providers/db/adapters.rb
# frozen_string_literal: true module Hanami module Providers class DB < Hanami::Provider::Source # @api public # @since 2.2.0 class Adapters # @api private # @since 2.2.0 ADAPTER_CLASSES = Hash.new(Adapter).update( sql: SQLAdapter ).freeze private_constant :ADAPTER_CLASSES extend Forwardable def_delegators :adapters, :[], :[]=, :each, :to_h # @api private # @since 2.2.0 def self.new_adapter(name) ADAPTER_CLASSES[name].new end # @api private # @since 2.2.0 attr_reader :adapters # @api private # @since 2.2.0 def initialize @adapters = {} end # @api private # @since 2.2.0 def initialize_copy(source) @adapters = source.adapters.dup source.adapters.each do |key, val| @adapters[key] = val.dup end end # @api private # @since 2.2.0 def adapter(key) adapters[key] ||= new(key) end # @api private # @since 2.2.0 def find(key) adapters.fetch(key) { new(key) } end # @api private # @since 2.2.0 def new(key) self.class.new_adapter(key) end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/providers/db/sql_adapter.rb
lib/hanami/providers/db/sql_adapter.rb
# frozen_string_literal: true module Hanami module Providers class DB < Hanami::Provider::Source # @api public # @since 2.2.0 class SQLAdapter < Adapter # @api public # @since 2.2.0 setting :extensions, mutable: true # @api public # @since 2.2.0 def extension(*extensions) self.extensions.concat(extensions).uniq! end # @api public # @since 2.2.0 def extensions config.extensions ||= [] end # @api private def configure_from_adapter(other_adapter) super return if skip_defaults? # As part of gateway configuration, every gateway will receive the "any adapter" here, # which is a plain `Adapter`, not an `SQLAdapter`. Its configuration will have been merged # by `super`, so no further work is required. return unless other_adapter.is_a?(self.class) extensions.concat(other_adapter.extensions).uniq! unless skip_defaults?(:extensions) end # @api private def configure_for_database(database_url) return if skip_defaults? configure_plugins configure_extensions(database_url) end # @api private private def configure_plugins return if skip_defaults?(:plugins) # Configure the plugin via a frozen proc, so it can be properly uniq'ed when configured # for multiple gateways. See `Hanami::Providers::DB::Config#each_plugin`. plugin(relations: :instrumentation, &INSTRUMENTATION_PLUGIN_CONFIG) plugin relations: :auto_restrictions end # @api private INSTRUMENTATION_PLUGIN_CONFIG = -> plugin { plugin.notifications = target["notifications"] }.freeze private_constant :INSTRUMENTATION_PLUGIN_CONFIG # @api private private def configure_extensions(database_url) return if skip_defaults?(:extensions) # Extensions for all SQL databases extension( :caller_logging, :error_sql, :sql_comments ) # Extensions for specific databases if database_url.to_s.start_with?(%r{postgres(ql)*://}) extension( :pg_array, :pg_enum, :pg_json, :pg_range ) end end # @api private def gateway_options {extensions: extensions} end # @api public # @since 2.2.0 def clear config.extensions = nil super end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/provider/source.rb
lib/hanami/provider/source.rb
# frozen_string_literal: true module Hanami module Provider class Source < Dry::System::Provider::Source attr_reader :slice def initialize(slice:, **options, &block) @slice = slice super(**options, &block) end def target_container = slice end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/actions.rb
lib/hanami/config/actions.rb
# frozen_string_literal: true require "dry/configurable" require "hanami/action" module Hanami class Config # Hanami actions config # # This exposes all the settings from the standalone `Hanami::Action` class, pre-configured with # sensible defaults for actions within a full Hanami app. It also provides additional settings # for further integration of actions with other full stack app components. # # @since 2.0.0 # @api public class Actions include Dry::Configurable # @!attribute [rw] cookies # Sets or returns a hash of cookie options for actions. # # The hash is wrapped by {Hanami::Config::Actions::Cookies}, which also provides an # `enabled?` method, returning true in the case of any options provided. # # @example # config.actions.cookies = {max_age: 300} # # @return [Hanami::Config::Actions::Cookies] # # @api public # @since 2.0.0 setting :cookies, default: {}, constructor: -> options { Cookies.new(options) } # @!attribute [rw] sessions # Sets or returns the session store (and its options) for actions. # # The given values are taken as an argument list to be passed to {Config::Sessions#initialize}. # # The configured session store is used when setting up the app or slice # {Slice::ClassMethods#router router}. # # @example # config.actions.sessions = :cookie, {secret: "xyz"} # # @return [Config::Sessions] # # @see Config::Sessions # @see Slice::ClassMethods#router # # @api public # @since 2.0.0 setting :sessions, constructor: proc { |storage, *options| Sessions.new(storage, *options) } # @!attribute [rw] csrf_protection # Sets or returns whether CSRF protection should be enabled for action classes. # # Defaults to true if {#sessions} is enabled. You can override this by explicitly setting a # true or false value. # # When true, this will include `Hanami::Action::CSRFProtection` in all action classes. # # @return [Boolean] # # @api public # @since 2.0.0 setting :csrf_protection # Returns the Content Security Policy config for actions. # # The resulting policy is set as a default `"Content-Security-Policy"` response header. # # @return [Hanami::Config::Actions::ContentSecurityPolicy] # # @api public # @since 2.0.0 attr_accessor :content_security_policy # Returns the proc to generate Content Security Policy nonce values. # # The current Rack request object is provided as an optional argument # to the proc, enabling the generation of nonces based on session IDs. # # @example Independent random nonce (default) # -> { SecureRandom.urlsafe_base64(16) } # # @example Session dependent nonce # ->(request) { Digest::SHA256.base64digest(request.session[:uuid])[0, 16] } # # @return [Proc] # # @api public # @since 2.3.0 setting :content_security_policy_nonce_generator, default: -> { SecureRandom.urlsafe_base64(16) } # @!attribute [rw] method_override # Sets or returns whether HTTP method override should be enabled for action classes. # # Defaults to true. You can override this by explicitly setting a # true or false value. # # When true, this will mount `Rack::MethodOverride` in the Rack middleware stack of the App. # # @return [Boolean] # # @api public # @since 2.1.0 setting :method_override, default: true # @!attribute [rw] name_inference_base # @api private # @since 2.1.0 setting :name_inference_base, default: "actions" # @!attribute [rw] view_name_inferrer # @api private # @since 2.1.0 setting :view_name_inferrer, default: Slice::ViewNameInferrer # @!attribute [rw] view_name_inference_base # @api private # @since 2.1.0 setting :view_name_inference_base, default: "views" # @api private attr_reader :base_config protected :base_config # @api private def initialize(*, **options) super() @base_config = Hanami::Action.config.dup @content_security_policy = ContentSecurityPolicy.new configure_defaults end # @api private def initialize_copy(source) super @base_config = source.base_config.dup @content_security_policy = source.content_security_policy.dup end private :initialize_copy # @api private def finalize!(app_config) @base_config.root_directory = app_config.root # A nil value for `csrf_protection` means it has not been explicitly configured # (neither true nor false), so we can default it to whether sessions are enabled self.csrf_protection = sessions.enabled? if csrf_protection.nil? if content_security_policy default_headers["Content-Security-Policy"] = content_security_policy.to_s end end # @api public # @since 2.3.0 def content_security_policy? = !!@content_security_policy private # Apply defaults for base config def configure_defaults self.default_headers = { "X-Frame-Options" => "DENY", "X-Content-Type-Options" => "nosniff", "X-XSS-Protection" => "1; mode=block" } end def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) elsif base_config.respond_to?(name) base_config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || base_config.respond_to?(name) || super end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/logger.rb
lib/hanami/config/logger.rb
# frozen_string_literal: true require "dry/configurable" require "dry/logger" module Hanami class Config # Hanami logger config # # @api public # @since 2.0.0 class Logger include Dry::Configurable # @return [Hanami::SliceName] # # @api private # @since 2.0.0 attr_reader :app_name # @return [Symbol] # # @api private # @since 2.0.0 attr_reader :env # @!attribute [rw] level # Sets or returns the logger's level. # # Defaults to `:info` for the production environment and `:debug` for all others. # # @return [Symbol] # # @api public # @since 2.0.0 setting :level # @!attribute [rw] stream # Sets or returns the logger's stream. # # This can be a file path or an `IO`-like object for the logger to write to. # # Defaults to `"log/test.log"` for the test environment and `$stdout` for all others. # # @return [String, #write] # # @api public # @since 2.0.0 setting :stream, default: $stdout # @!attribute [rw] formatter # Sets or returns the logger's formatter. # # This may be a name that matches a formatter registered with `Dry::Logger`, which includes # `:string`, `:rack` and `:json`. # # This may also be an instance of Ruby's built-in `::Logger::Formatter` or any compatible # object. # # Defaults to `:json` for the production environment, and `:rack` for all others. # # @return [Symbol, ::Logger::Formatter] # # @api public # @since 2.0.0 setting :formatter, default: :string # @!attribute [rw] template # Sets or returns log entry string template # # Defaults to `false`. # # @return [Boolean] # # @api public # @since 2.0.0 setting :template, default: :details # @!attribute [rw] filters # Sets or returns an array of attribute names to filter from logs. # # Defaults to `["_csrf", "password", "password_confirmation"]`. If you want to preserve # these defaults, append to this array rather than reassigning it. # # @return [Array<String>] # # @api public # @since 2.0.0 setting :filters, default: %w[_csrf password password_confirmation].freeze # @!attribute [rw] logger_constructor # Sets or returns the constructor proc to use for the logger instantiation. # # Defaults to either `Config#production_logger` or `Config#development_logger` # # @api public # @since 2.0.0 setting :logger_constructor # @!attribute [rw] options # Sets or returns a hash of options to pass to the {logger_constructor} when initializing # the logger. # # Defaults to `{}` # # @return [Hash] # # @api public # @since 2.0.0 setting :options, default: {} # Returns a new `Logger` config. # # You should not need to initialize this directly, instead use {Hanami::Config#logger}. # # @param env [Symbol] the Hanami env # @param app_name [Hanami::SliceName] # # @api private def initialize(env:, app_name:) @app_name = app_name @env = env case env when :development, :test config.level = :debug config.stream = File.join("log", "#{env}.log") if env == :test config.logger_constructor = method(:development_logger) else config.level = :info config.formatter = :json config.logger_constructor = method(:production_logger) end end # Returns a new instance of the logger. # # @return [logger_class] # # @api public # @since 2.0.0 def instance logger_constructor.call(env, app_name.name, **logger_constructor_options) end # Build an instance of a development logger # # This logger is used in both development and test # # @return [Dry::Logger::Dispatcher] # @since 2.0.0 # @api private def development_logger(_env, app_name, **options) Dry.Logger(app_name, **options) do |setup| setup .add_backend(log_if: -> entry { !entry.tag?(:rack) }) .add_backend(formatter: :rack, log_if: -> entry { entry.tag?(:rack) }) end end # Build an instance of a production logger # # This logger is used in both development and test # # @return [Dry::Logger::Dispatcher] # @since 2.0.0 # @api private def production_logger(_env, app_name, **options) Dry.Logger(app_name, **options) end private # @api private def logger_constructor_options {stream: stream, level: level, formatter: formatter, filters: filters, template: template, **options} end # @api private def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) else super end end # @api private def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || super end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/db.rb
lib/hanami/config/db.rb
# frozen_string_literal: true require "dry/configurable" module Hanami class Config # Hanami DB config # # @since 2.2.0 # @api public class DB include Dry::Configurable setting :configure_from_parent, default: true setting :import_from_parent, default: false private def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || super end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/views.rb
lib/hanami/config/views.rb
# frozen_string_literal: true require "dry/configurable" require "hanami/view" module Hanami class Config # Hanami views config # # This exposes all the settings from the standalone `Hanami::View` class, pre-configured with # sensible defaults for actions within a full Hanami app. It also provides additional settings # for further integration of views with other full stack app components. # # @since 2.1.0 # @api public class Views include Dry::Configurable # @api private # @since 2.1.0 attr_reader :base_config protected :base_config # @api private # @since 2.1.0 def initialize(*) super @base_config = Hanami::View.config.dup configure_defaults end # @api private # @since 2.1.0 def initialize_copy(source) super @base_config = source.base_config.dup end private :initialize_copy # @api private # @since 2.1.0 def finalize! return self if frozen? base_config.finalize! super end private def configure_defaults self.layout = "app" end # An inflector for views is not configurable via `config.views.inflector` on an # `Hanami::App`. The app-wide inflector is already configurable # there as `config.inflector` and will be used as the default inflector for views. # # A custom inflector may still be provided in an `Hanami::View` subclass, via # `config.inflector=`. NON_FORWARDABLE_METHODS = %i[inflector inflector=].freeze private_constant :NON_FORWARDABLE_METHODS def method_missing(name, *args, &block) return super if NON_FORWARDABLE_METHODS.include?(name) if config.respond_to?(name) config.public_send(name, *args, &block) elsif base_config.respond_to?(name) base_config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) return false if NON_FORWARDABLE_METHODS.include?(name) config.respond_to?(name) || base_config.respond_to?(name) || super end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/router.rb
lib/hanami/config/router.rb
# frozen_string_literal: true require "dry/configurable" require_relative "../slice/routing/resolver" module Hanami class Config # Hanami router config # # @since 2.0.0 # @api private class Router include Dry::Configurable # Base config is provided so router config can include the `base_url` attr_reader :base_config private :base_config # @api private # @since 2.0.0 def initialize(base_config) @base_config = base_config end setting :resolver, default: Slice::Routing::Resolver # @api private # @since 2.0.0 def options {base_url: base_config.base_url} end private def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || super end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/console.rb
lib/hanami/config/console.rb
# frozen_string_literal: true require "dry/configurable" module Hanami class Config # Hanami console config # # @since 2.3.0 # @api public class Console include Dry::Configurable # @!attribute [rw] engine # Sets or returns the interactive console engine to be used by `hanami console`. # Supported values are `:irb` (default) and `:pry`. # # @example # config.console.engine = :pry # # @return [Symbol] # # @api public # @since 2.3.0 setting :engine, default: :irb # Returns the complete list of extensions to be used in the console # # @example # config.console.include MyExtension, OtherExtension # config.console.include ThirdExtension # # config.console.extensions # # => [MyExtension, OtherExtension, ThirdExtension] # # @return [Array<Module>] # # @api public # @since 2.3.0 def extensions = @extensions.dup.freeze # Define a module extension to be included in the console # # @param mod [Module] one or more modules to be included in the console # @return [void] # # @api public # @since 2.3.0 def include(*mod) @extensions.concat(mod).uniq! end # @api private def initialize @extensions = [] end private # @api private def initialize_copy(source) super @extensions = [*source.extensions] end def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || super end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/null_config.rb
lib/hanami/config/null_config.rb
# frozen_string_literal: true require "dry/configurable" module Hanami class Config # NullConfig can serve as a fallback config object when out-of-gem config objects are not # available (specifically, when the hanami-controller, hanami-router or hanami-view gems are not # loaded) class NullConfig include Dry::Configurable def finalize!(*) end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/assets.rb
lib/hanami/config/assets.rb
# frozen_string_literal: true require "dry/configurable" require "hanami/assets" module Hanami class Config # Hanami assets config # # This exposes all the settings from the standalone `Hanami::Assets` class, pre-configured with # sensible defaults for actions within a full Hanami app. It also provides additional settings # for further integration of assets with other full stack app components. # # @since 2.1.0 # @api public class Assets include Dry::Configurable # @!attribute [rw] serve # Serve static assets. # # When this is `true`, the app will serve static assets. # # If not set, this will: # # * Check if the `HANAMI_SERVE_ASSETS` environment variable is set to `"true"`. # * If not, it will check if the app is running in the `development` or `test` environment. # # @example # config.assets.serve = true # # @return [Hanami::Config::Actions::Cookies] # # @api public # @since 2.1.0 setting :serve # @api private attr_reader :base_config protected :base_config # @api private def initialize(*, **options) super() @base_config = Hanami::Assets::Config.new(**options) configure_defaults end # @api private def initialize_copy(source) super @base_config = source.base_config.dup end private :initialize_copy private def configure_defaults self.serve = if ENV.key?("HANAMI_SERVE_ASSETS") ENV["HANAMI_SERVE_ASSETS"] == "true" else Hanami.env?(:development, :test) end end def method_missing(name, *args, &block) if config.respond_to?(name) config.public_send(name, *args, &block) elsif base_config.respond_to?(name) base_config.public_send(name, *args, &block) else super end end def respond_to_missing?(name, _include_all = false) config.respond_to?(name) || base_config.respond_to?(name) || super end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false