Created
September 12, 2017 12:11
-
-
Save Agowan/63de9f406d409c8a4f1169bbcbae585c to your computer and use it in GitHub Desktop.
Slim api with rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module Api | |
class BaseController < ActionController::Metal | |
include ActiveSupport::Rescuable | |
# Add if you want to have force ssl | |
# include ActionController::ForceSSL | |
# Add if you want callbacks i.e. before_action | |
# include AbstractController::Callbacks | |
# Add if you want helpers | |
# include ActionController::Helpers | |
# Add timings if in development | |
if Rails.env.development? || Rails.env.test? | |
include ActionController::Instrumentation | |
ActiveSupport.run_load_hooks(:action_controller, self) | |
end | |
def render(options = {}) | |
self.status = options[:status] || 200 | |
self.content_type = 'application/json' | |
body = options[:text] | |
body = Oj.dump(options[:json], mode: :compat) if body.nil? | |
headers['Content-Length'] = body.bytesize.to_s | |
self.response_body = body | |
end | |
def sanitize(sql, query) | |
ActiveRecord::Base.send(:sanitize_sql, [sql, query]) | |
end | |
# short for executing a query | |
def execute(sql) | |
ActiveRecord::Base.connection.execute(sql) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module Api | |
class ArticlesController < BaseController | |
def index | |
# Let the OJ gem handle the json rendering | |
sql = Articles.where(language: 'sv').order('sort_order').to_sql | |
render json: execute(sql).to_a | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module Api | |
class ArticlesController < BaseController | |
# Let postgresql handle the json rendering | |
def index | |
sql = "SELECT to_json(array_agg(articles)) as json FROM articles WHERE language = 'sv'" | |
render text: execute(sql).first['json'] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment