Skip to content

Instantly share code, notes, and snippets.

@dkolb
Last active December 1, 2018 22:51
Show Gist options
  • Save dkolb/9a4a4794b1deacfd9043a4372ae490ab to your computer and use it in GitHub Desktop.
Save dkolb/9a4a4794b1deacfd9043a4372ae490ab to your computer and use it in GitHub Desktop.
Airrecord Patches
module AirrecordTableUtilities
def self.included base
base.extend ClassMethods
base.include InstanceMethods
end
module ClassMethods
def map_field(method_name, field_name)
define_method method_name do
self[field_name]
end
define_method "#{method_name.to_s}=" do |new_value|
self[field_name] = new_value
end
end
def new_from_mapped_fields(fields)
record = self.new({})
fields.each do |field_name, new_value|
record.send("#{field_name.to_s}=", new_value)
end
record
end
end
module InstanceMethods
def set_from_mapped_fields(fields)
fields.each do |field_name, new_value|
self.send("#{field_name.to_s}=", new_value)
end
end
def changed?
!self.updated_keys.empty?
end
end
end
Airrecord::Table.include AirrecordTableUtilities
class Member < Airrecord::Table
self.table = 'Members'
map_field :full_name, 'Full Name'
end
class MeController < ApplicationController
def show
@member = Member.find(session[:user_record])
end
def update_profile
member = Member.find(session[:user_record])
member.set_from_mapped_fields(params[:member])
if member.changed?
flash[:success] = "Updated your records!"
else
flash[:notice] = "No changes detected."
end
member.save
redirect_to action: "show"
end
end
<h2>Member Info</h2>
<%= form_tag(controller: 'me', action: 'update_profile') do %>
<p><%= label(:member, :full_name, 'Full Name') %>:
<%= text_field(:member, :full_name) %>
</p>
<p><%= button_tag 'Save Changes' %>
</p>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment