Overriding a route allows you to change or completely replace a Forest’s route behavior.
Changing Forest’s behavior
To achieve this, use existing snippets of default routes and modify them according to your needs.
Here are a few examples:
Use extended search by default
if ForestLiana::UserSpace.const_defined?('CompanyController')
ForestLiana::UserSpace::CompanyController.class_eval do
alias_method :default_index, :index
alias_method :default_count, :count
# Get a list of Companies
def index
params['searchExtended'] = '1'
default_index
end
# Get a number of Companies
def count
params['searchExtended'] = '1'
default_count
end
end
end
With this snippet, only the companies collection would use extended search by default.
Using extended search is less performant than default search. Use this wisely.
Protect a specific record
if ForestLiana::UserSpace.const_defined?('CompanyController')
ForestLiana::UserSpace::CompanyController.class_eval do
alias_method :default_destroy, :destroy
def destroy
if params["id"] == "50"
render status: 403, plain: 'This record is protected, you cannot remove it.'
else
default_destroy
end
end
end
end
Replacing Forest’s behavior
To achieve this, simply remove the next() statement of any route:
if ForestLiana::UserSpace.const_defined?('CompanyController')
ForestLiana::UserSpace::CompanyController.class_eval do
# Create a Company
def create
# >> Add your own logic here <<
end
end
end
For instance, if you have a Users collection, you might want to create your users via your own api:
require 'net/http'
require 'uri'
if ForestLiana::UserSpace.const_defined?('UserController')
ForestLiana::UserSpace::UserController.class_eval do
# Create a User
def create
forest_authorize!('add', forest_user, @resource)
begin
response = Net::HTTP.post URI('https://<your-api>/users'), params.to_json, "Content-Type" => "application/json"
render serializer: nil, json: render_record_jsonapi(response.body)
rescue => errors
render serializer: nil, json: JSONAPI::Serializer.serialize_errors(errors), status: 400
end
end
end
end