Skip to content

Instantly share code, notes, and snippets.

@khash
Created February 12, 2021 05:08
Show Gist options
  • Save khash/a17aba6ebd0f19f32999c719dd15854d to your computer and use it in GitHub Desktop.
Save khash/a17aba6ebd0f19f32999c719dd15854d to your computer and use it in GitHub Desktop.
Rails No Hotwire
<%= button_to switch_path do %>
<%= switch.state %>
<%= hidden_field_tag :state, switch.state %>
<% end %>
class Switch
def state
@state
end
def state= (value)
@state = value
end
def save
File.open(Switch.switch_path, "w+") do |f|
f.write(@state)
end
end
def self.load
switch = Switch.new
switch.state = File.read(switch_path)
switch
end
private
def self.switch_path
File.join(Rails.root, 'tmp', 'switch.txt')
end
end
class SwitchController < ApplicationController
before_action :set_switch
def update
if params[:state] == 'on'
@switch.state = 'off'
else
@switch.state = 'on'
end
@switch.save
render partial: 'show', locals: { switch: @switch }
end
def show
render partial: 'show', locals: { switch: @switch }
end
private
def set_switch
@switch = Switch.load
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment