### BHF API Routes and curl Examples Source: https://context7.com/antpaw/bhf/llms.txt Lists available RESTful routes and provides curl commands for common CRUD operations. ```ruby # Available routes after mounting BHF engine at /admin # GET /admin => Dashboard/index # GET /admin/page/:page => Pages#show (list platforms) # GET /admin/:platform/entries/new => New entry form # POST /admin/:platform/entries => Create entry # GET /admin/:platform/entries/:id => Show entry (HTML/JSON) # GET /admin/:platform/entries/:id/edit => Edit entry form # PATCH /admin/:platform/entries/:id => Update entry # DELETE /admin/:platform/entries/:id => Delete entry # PUT /admin/:platform/entries/sort => Reorder entries # POST /admin/:platform/entries/:id/duplicate => Duplicate entry # Example API usage with curl: # Get entry as JSON curl -X GET "http://localhost:3000/admin/users/entries/1.json" \ -H "Cookie: _session_id=YOUR_SESSION" # Create new entry curl -X POST "http://localhost:3000/admin/posts/entries" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "X-CSRF-Token: YOUR_TOKEN" \ -H "Cookie: _session_id=YOUR_SESSION" \ -d "post[title]=New Post&post[content]=Content here&post[published]=true" # Update entry curl -X PATCH "http://localhost:3000/admin/posts/entries/1" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "X-CSRF-Token: YOUR_TOKEN" \ -H "Cookie: _session_id=YOUR_SESSION" \ -d "post[title]=Updated Title" # Delete entry curl -X DELETE "http://localhost:3000/admin/posts/entries/1" \ -H "X-CSRF-Token: YOUR_TOKEN" \ -H "Cookie: _session_id=YOUR_SESSION" ``` -------------------------------- ### Build and Publish bhf Gem Source: https://github.com/antpaw/bhf/blob/main/README.md Steps to build and publish the bhf gem. Ensure you have juwelier installed and commit any version changes before building. ```bash gem install juwelier rake gemspec:generate git commit -m "Regenerate gemspec for version 1.0.0.beta11" -a gem build bhf.gemspec gem push bhf-1.0.0.beta11.gem ``` -------------------------------- ### GET /admin/:platform/entries/:id Source: https://context7.com/antpaw/bhf/llms.txt Retrieves a specific entry from a platform. Supports both HTML and JSON formats. ```APIDOC ## GET /admin/:platform/entries/:id ### Description Retrieves a specific entry from the specified platform. Append .json to the URL to receive the response in JSON format. ### Method GET ### Endpoint /admin/:platform/entries/:id ### Parameters #### Path Parameters - **platform** (string) - Required - The name of the platform/model - **id** (integer/string) - Required - The unique identifier of the entry ### Response #### Success Response (200) - **entry** (object) - The requested entry data ``` -------------------------------- ### Configure BHF Gem and Initializer Source: https://context7.com/antpaw/bhf/llms.txt Add the gem to your Gemfile and define global settings like authentication keys, account models, and asset paths in the initializer. ```ruby # Gemfile gem 'bhf' # After bundle install, create the initializer # config/initializers/bhf.rb Bhf.configure do |config| # Custom logo for admin interface config.logo = lambda { |area| 'my_logo.svg' } # Redirect path on login failure config.on_login_fail = :root_url # Path helper for logout link config.logout_path = :logout_path # Session key for storing account ID config.session_account_id = :admin_account_id # Session key for authentication status config.session_auth_name = :is_admin # Model used for admin accounts config.account_model = 'User' # Method to find account by ID config.account_model_find_method = 'find' # Additional CSS files to include config.css << 'custom_admin_styles' # Additional JS files to include config.js << 'custom_admin_scripts' # Abstract settings files for shared configurations config.abstract_settings << 'abstract' end ``` -------------------------------- ### POST /admin/:platform/entries Source: https://context7.com/antpaw/bhf/llms.txt Creates a new entry within the specified platform. ```APIDOC ## POST /admin/:platform/entries ### Description Creates a new entry for the given platform using form-encoded data. ### Method POST ### Endpoint /admin/:platform/entries ### Parameters #### Path Parameters - **platform** (string) - Required - The name of the platform/model #### Request Body - **[model_name]** (object) - Required - The attributes for the new entry ``` -------------------------------- ### Order Configuration with User Scope Source: https://context7.com/antpaw/bhf/llms.txt Sets up the Order model configuration in BHF, including user-specific data scoping for different roles. ```yaml model: Order table: user_scope: managed_orders display: - id - customer - total - status - created_at scope: - pending - processing - completed - cancelled ``` -------------------------------- ### Product Configuration in BHF YAML Source: https://context7.com/antpaw/bhf/llms.txt Defines the display, form, and search settings for the Product model within the BHF admin interface. ```yaml model: Product table: display: - id - name - price - category - stock_count - active types: active: toggle price: number search: custom_admin_search custom_search: true per_page: 50 hide_delete: false show_duplicate: true form: display: - name - description - price - category - tags - images types: description: markdown images: activestorage_attachments multipart: true links: category: categories tags: tags exclude: - created_at - updated_at show: display: - id - name - description - price - category - created_at hooks: before_save: prepare_for_admin_save after_save: process_admin_save after_load: setup_for_admin ``` -------------------------------- ### PUT /admin/:platform/entries/sort Source: https://context7.com/antpaw/bhf/llms.txt Reorders entries within a platform. ```APIDOC ## PUT /admin/:platform/entries/sort ### Description Updates the order of entries for the specified platform. ### Method PUT ### Endpoint /admin/:platform/entries/sort ### Parameters #### Path Parameters - **platform** (string) - Required - The name of the platform/model ``` -------------------------------- ### Implement Session Authentication and User Roles Source: https://context7.com/antpaw/bhf/llms.txt Configures session-based authentication in the controller and defines required role-based methods in the User model. ```ruby # app/controllers/sessions_controller.rb class SessionsController < ApplicationController def create user = User.find_by(email: params[:email]) if user&.authenticate(params[:password]) && user.admin? # Set the session variables BHF expects session[:is_admin] = true session[:admin_account_id] = user.id redirect_to bhf_path, notice: 'Logged in successfully' else flash.now[:error] = 'Invalid credentials' render :new end end def destroy session[:is_admin] = nil session[:admin_account_id] = nil redirect_to root_path, notice: 'Logged out' end end # app/models/user.rb - Role methods for BHF class User < ApplicationRecord has_many :user_roles has_many :roles, through: :user_roles has_many :areas, through: :roles # Returns roles for loading YAML config files def bhf_roles roles.map { |r| OpenStruct.new(identifier: r.slug) } end # Returns roles specific to an area def bhf_area_roles(area) roles.joins(:areas).where(areas: { slug: area }).map do |r| OpenStruct.new(identifier: r.slug) end end # Returns available admin areas for this user def bhf_areas areas.distinct.map do |area| OpenStruct.new( identifier: area.slug, link: area.default_link, to_bhf_s: area.name ) end end end ``` -------------------------------- ### Define Admin Interface with YAML Source: https://context7.com/antpaw/bhf/llms.txt Configure which models appear in the admin dashboard and specify table columns, search settings, and form field types. ```yaml # config/bhf.yml pages: - main: - users: model: User table: display: - id - email - name - created_at search: true per_page: 25 form: display: - email - name - password - role types: password: password - posts: model: Post table: display: - id - title - author - published - created_at sortable: true quick_edit: true form: display: - title - content - author - category - published types: content: wysiwyg published: boolean - settings: - categories: model: Category table: scope: - active - archived form: display: - name - description ``` -------------------------------- ### Article Model Integration for BHF (Mongoid) Source: https://context7.com/antpaw/bhf/llms.txt Shows how to integrate BHF functionalities into a Mongoid Article document, including custom display and search. ```ruby class Article include Mongoid::Document include Mongoid::Timestamps field :title, type: String field :content, type: String field :published, type: Boolean, default: false field :views, type: Integer, default: 0 belongs_to :author, class_name: 'User' has_many :comments embeds_many :revisions # Custom display for BHF def to_bhf_s title.presence || "Article ##{id}" end # Custom search for Mongoid def self.bhf_admin_search(params) text = params['text'] return all if text.blank? any_of( { title: /#{Regexp.escape(text)}/i }, { content: /#{Regexp.escape(text)}/i } ) end end ``` -------------------------------- ### Configure BHF Admin Platforms Source: https://context7.com/antpaw/bhf/llms.txt Defines the structure, form fields, and table displays for admin platforms in config/bhf.yml. ```yaml pages: - main: - posts: form: display: - title - content - author - category - tags - comments types: # belongs_to - select dropdown (default) author: select # belongs_to - radio buttons category: radio # has_and_belongs_to_many - checkboxes (default) tags: check_box # has_many - read-only list comments: static # Link to related platform for creating/editing links: author: users # Links to users platform category: categories # Links to categories platform tags: tags # Links to tags platform comments: false # Disable link for comments table: display: - title - author - category - tags_count - created_at types: # Custom display types for table columns author: default # Shows linked record name category: default # Shows linked record name - categories: table: display: - name - posts # has_many relationship count types: posts: default # Shows count of related records form: display: - name - parent # belongs_to self-reference - posts # has_many - static list types: posts: static # Read-only, shows linked records parent: select # Dropdown for parent category ``` -------------------------------- ### User Model Integration for BHF Source: https://context7.com/antpaw/bhf/llms.txt Demonstrates integrating BHF functionalities into an ActiveRecord User model, including custom display, search scopes, and save hooks. ```ruby class User < ApplicationRecord has_many :posts has_many :orders belongs_to :role # Custom display string for BHF interface def to_bhf_s "#{name} (#{email})" end # Custom search scope for admin scope :bhf_admin_search, ->(params) { text = params['text'] return all if text.blank? where('name ILIKE ? OR email ILIKE ?', "%#{text}%", "%#{text}%") } # Hook called after record is loaded in admin def setup_for_admin # Initialize any admin-specific attributes end # Hook called before save in admin def prepare_for_admin_save(params) self.updated_by = params[:current_admin_id] if params[:current_admin_id] end # Hook called after save in admin def process_admin_save(params) AdminActivityLog.create( action: new_record? ? 'create' : 'update', model: self.class.name, record_id: id ) end # Return additional data for AJAX responses def to_bhf_hash { avatar_url: avatar.attached? ? avatar.url : nil, full_name: "#{first_name} #{last_name}" } end # Control edit permissions per record def bhf_can_edit?(options) !locked? && !archived? end # Define BHF area for frontend editing def bhf_area(options) 'main' end # Duplicate hook - called before duplicate save def before_bhf_duplicate(original) self.email = "copy_#{original.email}" self.name = "Copy of #{original.name}" end # Duplicate hook - called after duplicate save def after_bhf_duplicate(original) original.tags.each { |tag| self.tags << tag } end end ``` -------------------------------- ### Use bhf_edit Helper in Views Source: https://context7.com/antpaw/bhf/llms.txt Adds admin edit links to frontend views, supporting custom platforms and specific admin areas. ```erb

<%= @post.title %>

<%= bhf_edit @post do %> Edit Post <% end %>
By <%= @post.author.name %> <%= @post.created_at.strftime('%B %d, %Y') %>
<%= @post.content.html_safe %>
<%= bhf_edit @post, platform_name: 'articles' do %> Edit as Article <% end %> <%= bhf_edit @post, area: 'content_management' do %> Edit in CMS <% end %>
<% @products.each do |product| %>
<%= image_tag product.image_url %>

<%= product.name %>

<%= number_to_currency product.price %>

<%= bhf_edit product, area: 'inventory' do %> <% end %>
<% end %>
``` -------------------------------- ### POST /admin/:platform/entries/:id/duplicate Source: https://context7.com/antpaw/bhf/llms.txt Duplicates an existing entry. ```APIDOC ## POST /admin/:platform/entries/:id/duplicate ### Description Creates a copy of an existing entry. ### Method POST ### Endpoint /admin/:platform/entries/:id/duplicate ### Parameters #### Path Parameters - **platform** (string) - Required - The name of the platform/model - **id** (integer/string) - Required - The unique identifier of the entry to duplicate ``` -------------------------------- ### Mount BHF Engine in Routes Source: https://context7.com/antpaw/bhf/llms.txt Define the URL path for the admin interface within the Rails routes file, supporting both single and multi-area configurations. ```ruby # config/routes.rb Rails.application.routes.draw do # Mount BHF at /admin path mount Bhf::Engine => '/admin', as: 'bhf' # Or mount with an area parameter for multi-area setup mount Bhf::Engine => '/admin/:bhf_area', as: 'bhf_area' # Your other application routes root to: 'home#index' end ``` -------------------------------- ### Manager Order Configuration Source: https://context7.com/antpaw/bhf/llms.txt Configures the Order model for the manager area, using a 'team_orders' user scope. ```yaml model: Order table: user_scope: team_orders ``` -------------------------------- ### Sort entries via cURL Source: https://context7.com/antpaw/bhf/llms.txt Updates the order of entries for sortable platforms using a PUT request. ```bash curl -X PUT "http://localhost:3000/admin/categories/entries/sort" \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "X-CSRF-Token: YOUR_TOKEN" \ -H "Cookie: _session_id=YOUR_SESSION" \ -d "order[0]=3_categories&order[1]=1_categories&order[2]=2_categories" ``` -------------------------------- ### Duplicate entry via cURL Source: https://context7.com/antpaw/bhf/llms.txt Creates a duplicate of an existing entry using a POST request. ```bash curl -X POST "http://localhost:3000/admin/products/entries/1/duplicate" \ -H "X-CSRF-Token: YOUR_TOKEN" \ -H "Cookie: _session_id=YOUR_SESSION" ``` -------------------------------- ### Admin Order Configuration Source: https://context7.com/antpaw/bhf/llms.txt Defines the display fields for all orders in the admin area of BHF. ```yaml model: Order table: display: - id - customer - total - status - assigned_to - created_at ``` -------------------------------- ### Category Configuration in BHF YAML Source: https://context7.com/antpaw/bhf/llms.txt Configures the table display and form fields for the Category model in BHF. ```yaml model: Category table: hide: false display: - name - products_count form: display: - name - parent_category ``` -------------------------------- ### DELETE /admin/:platform/entries/:id Source: https://context7.com/antpaw/bhf/llms.txt Deletes an existing entry from the specified platform. ```APIDOC ## DELETE /admin/:platform/entries/:id ### Description Removes an entry from the system. ### Method DELETE ### Endpoint /admin/:platform/entries/:id ### Parameters #### Path Parameters - **platform** (string) - Required - The name of the platform/model - **id** (integer/string) - Required - The unique identifier of the entry ``` -------------------------------- ### PATCH /admin/:platform/entries/:id Source: https://context7.com/antpaw/bhf/llms.txt Updates an existing entry within the specified platform. ```APIDOC ## PATCH /admin/:platform/entries/:id ### Description Updates the attributes of an existing entry. ### Method PATCH ### Endpoint /admin/:platform/entries/:id ### Parameters #### Path Parameters - **platform** (string) - Required - The name of the platform/model - **id** (integer/string) - Required - The unique identifier of the entry #### Request Body - **[model_name]** (object) - Required - The attributes to update ``` -------------------------------- ### Perform AJAX operations Source: https://context7.com/antpaw/bhf/llms.txt Handles CRUD operations via AJAX by setting the X-Requested-With header and parsing JSON responses. ```javascript // JavaScript example for quick edit operations // BHF automatically handles these when using the built-in JS // Create entry via AJAX fetch('/admin/posts/entries', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, body: new URLSearchParams({ 'post[title]': 'AJAX Created Post', 'post[content]': 'Content created via quick edit' }) }) .then(response => response.json()) .then(data => { // Response includes: // - to_bhf_s: Display string // - object_id: New record ID // - Plus column values for table updates console.log('Created:', data.to_bhf_s, 'ID:', data.object_id); }); // Update entry via AJAX fetch('/admin/posts/entries/1', { method: 'PATCH', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, body: new URLSearchParams({ 'post[title]': 'Updated via AJAX' }) }) .then(response => response.json()) .then(data => { // Update table row with new column values Object.keys(data).forEach(key => { const cell = document.querySelector(`[data-column="${key}"]`); if (cell) cell.innerHTML = data[key]; }); }); // Delete entry via AJAX fetch('/admin/posts/entries/1', { method: 'DELETE', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content } }) .then(response => response.json()) .then(data => { // Remove row from table document.querySelector(`#entry_1`)?.remove(); }); ``` -------------------------------- ### Define Revision Model Source: https://context7.com/antpaw/bhf/llms.txt Defines an embedded Mongoid document for article revisions. ```ruby class Revision include Mongoid::Document include Mongoid::Timestamps field :content, type: String field :version, type: Integer embedded_in :article def to_bhf_s "Version #{version}" end end ``` -------------------------------- ### Configure form field types Source: https://context7.com/antpaw/bhf/llms.txt Defines field types for model attributes in bhf.yml to customize the admin interface input controls. ```yaml # config/bhf.yml - Form field type examples pages: - content: - articles: form: display: - title - slug - excerpt - content - featured_image - gallery_images - published_at - views_count - is_featured - category - tags - author - meta_data types: # Text fields title: string # Single line text input slug: string # Single line text excerpt: text # Multi-line textarea # Rich text editors content: wysiwyg # WYSIWYG HTML editor (MooEditable) # content: markdown # Markdown editor with preview # content: rich_text # Trix editor (ActionText) # File uploads featured_image: image_file # Image upload gallery_images: activestorage_attachments # Multiple attachments # Date/time fields published_at: date # Date picker # published_at: datetime # Date and time picker # published_at: time # Time only picker # Numeric fields views_count: number # Number input price: number # Decimal/float input # Boolean fields is_featured: boolean # Checkbox # is_featured: toggle # Toggle switch in table view # Special fields password: password # Password input (masked) coordinates: mappin # Map pin selector for lat/lng settings: hash # Key-value hash editor options: array # Array field editor # Relationship fields category: select # Dropdown select for belongs_to # category: radio # Radio buttons for belongs_to tags: check_box # Checkboxes for has_many/HABTM author: static # Read-only display # Hidden/static id: static # Read-only display type: type # STI type selector legacy_id: hidden # Hidden field ``` -------------------------------- ### Customize BHF Interface Labels Source: https://context7.com/antpaw/bhf/llms.txt Overrides default BHF labels, messages, and titles using Rails I18n in config/locales/bhf.en.yml. ```yaml # config/locales/bhf.en.yml en: bhf: page_title: "%{title} Admin Panel" # Custom platform titles platforms: users: title: one: "User" other: "Users" zero: "No Users" scopes: active: "Active Users" inactive: "Inactive Users" infos: email: "Enter a valid email address" role: "Assign user permissions" posts: title: one: "Article" other: "Articles" scopes: published: "Published" draft: "Drafts" infos: content: "Use markdown for formatting" # Admin areas areas: links: content: "Content Management" users: "User Administration" settings: "System Settings" page_title: "%{area} - %{title} Admin" # Form helpers helpers: form: buttons: save: "Save %{platform_title}" and_edit: "Save & Continue Editing" and_add: "Save & Add Another" entry: new: "Create New %{platform_title}" edit: "Edit %{platform_title}" delete: "Delete %{platform_title}" duplicate: "Duplicate %{platform_title}" models: user: new: "Add New User" edit: "Edit User Profile" promts: confirm: "Are you sure you want to delete this %{platform_title}?" searchform: placeholder: "Search..." # Pagination pagination: info: default: "Showing %{offset_start}-%{offset_end} of %{count} %{name}" one: "Showing 1 %{name}" zero: "No %{name} found" # ActiveRecord model names activerecord: models: user: one: "User" other: "Users" post: one: "Post" other: "Posts" # Custom attribute labels attributes: user: email: "Email Address" created_at: "Member Since" post: title: "Post Title" content: "Body Content" # Success/error messages notices: models: user: create: success: "User account created successfully!" update: success: "User profile updated!" post: duplicate: success: "Post duplicated! You can now edit the copy." messages: create: success: "%{model} was successfully created" update: success: "%{model} was successfully updated" destroy: success: "%{model} was successfully deleted" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.