Skip to content

Instantly share code, notes, and snippets.

@kurenn
Last active March 29, 2017 21:16
Show Gist options
  • Select an option

  • Save kurenn/4421177 to your computer and use it in GitHub Desktop.

Select an option

Save kurenn/4421177 to your computer and use it in GitHub Desktop.

Revisions

  1. Abraham renamed this gist Dec 31, 2012. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Abraham created this gist Dec 31, 2012.
    68 changes: 68 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    ##Userable
    module Userable
    def self.included(base)
    base.has_one :user, :as => :userable, :dependent => :destroy, :autosave => true
    base.validate :user_must_be_valid
    base.alias_method_chain :user, :autobuild
    base.extend ClassMethods
    base.define_user_accessors
    end

    def user_with_autobuild
    user_without_autobuild || build_user
    end

    def method_missing(meth, *args, &blk)
    user.send(meth, *args, &blk)
    rescue NoMethodError
    super
    end

    protected

    def user_must_be_valid
    unless user.valid?
    user.errors.each do |attr, message|
    errors.add(attr, message)
    end
    end
    end

    module ClassMethods
    def define_user_accessors
    all_attributes = User.columns.map(&:name)
    all_attributes << "password"
    all_attributes << "password_confirmation"
    ignored_attributes = ["created_at", "updated_at", "userable_type", "encrypted_password", "id", "userable_id"]
    attributes_to_delegate = all_attributes - ignored_attributes
    attributes_to_delegate.each do |attrib|
    class_eval <<-RUBY
    def #{attrib}
    user.#{attrib}
    end

    def #{attrib}=(value)
    self.user.#{attrib} = value
    end

    def #{attrib}?
    self.user.#{attrib}?
    end
    RUBY
    end
    end
    end
    end

    ##Act as user
    class ActiveRecord::Base
    def self.acts_as_user
    include Userable
    end
    end

    ##User model
    belongs_to :userable, polymorphic: true

    ##Polymorphic model
    acts_as_user