Skip to content

Instantly share code, notes, and snippets.

@kaspth
Last active April 6, 2023 16:57
Show Gist options
  • Save kaspth/b037b87199615faf22a5066c70d6fd3e to your computer and use it in GitHub Desktop.
Save kaspth/b037b87199615faf22a5066c70d6fd3e to your computer and use it in GitHub Desktop.
# app/controllers/feeds_controller.rb
class FeedsController < ApplicationController
before_action :set_feed
def show
# Not sure if I like this but there could be something similar to interactors?
action do
_1.success.html { redirect_to @feed, notice: "Success" }
_1.success.json
_1.unprocessible { render :new }
end
end
private
def set_feed
@feed = … # Instance variables are copied to actions, same as they are for views.
end
end
module ActionController::ActionObjects
def self.included(klass)
klass.mattr_reader :action_objects, default: Hash.new do |objects, action_name|
objects.store action_name, begin const_get action_name.classify; rescue NameError; nil end
end
klass.helper_method :action
end
def action
# Probably needs special handling when we're called from the view side so the constant lookup works.
action_objects[action_name]&.run(view_assigns)
end
end
class ActionController::ActionObject
def self.run(...)
new(...).tap { _1.process if @_process_added }
end
attr_reader :params
def initialize(params, assigns)
@params = params
assign assigns
end
include Rails.application.routes.url_helpers
def self.method_added(method)
@_process_added = true if method == :process
end
private
def assign(assigns)
assigns.each { instance_variable_set :"@#{_1}", _2 }
end
end
# Zeitwerk will automatically load this:
# app/controllers/feeds_controller/show.rb
class FeedsController::Show < ActionController::ActionObject
# An optional method to implement, which is called when the action is initalized.
def process # Or respond?
synchronize
end
def entries
@entries ||= @feed.entries.order(published_at: published_at_order).per_page(params[:per_page])
end
# Can't remember what this was for, lol?
def actions
end
private
def synchronize
unless @feed.last_checked_at?
SyncFeedJob.perform_now(@feed, source: :feeds_show)
@feed.reload
end
end
def published_at_order
@feed.itunes_type == "serial" ? :asc : :desc
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment