Created
February 12, 2021 05:08
-
-
Save khash/a17aba6ebd0f19f32999c719dd15854d to your computer and use it in GitHub Desktop.
Rails No Hotwire
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
<%= button_to switch_path do %> | |
<%= switch.state %> | |
<%= hidden_field_tag :state, switch.state %> | |
<% 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
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 |
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
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