Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

August Lilleaas http://august.lilleaas.net

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

RSpec extension: testing attr_protected and attr_accessible

Include this module in a spec or inside the Spec::Runner.configure block in the spec_helper.rb. Because i suck, should_not is not working as expected. Usage:

class User < ActiveRecord::Base
  # either 
  attr_accessible :username, :full_name
  # or
  attr_protected :admin, :foo
end

# ...

it "should protect admin and foo" do
  @user.should protect_attributes(:admin, :foo)
end


Here goes:

module CustomExpectations
  class ProtectAttributes
    def initialize(*attributes)
      @attributes = attributes
    end
    
    def matches?(target)
      @target = target
      
      calculate_protected_methods
      perform_check
    end
    
    def failure_message
      "expected #{@failed_attribute} to be protected"
    end
    
    def negative_failure_message
      "expected #{@failed_attribute} to not be protected"
    end
    
    private
    
    def calculate_protected_methods
      read = proc {|var| @target.instance_eval { self.class.read_inheritable_attribute(var) } }
      accessible = read.call("attr_accessible")
      protekted = read.call("attr_protected")
      all = @target.class.column_names.map(&:to_sym)
      
      @protected = []
      @protected << protekted if protekted
      @protected << (all - accessible) if accessible
      @protected.flatten!
      
      @accessible = all - @protected
    end
    
    def perform_check
      failed_attributes = (@attributes & @accessible)
      @failed_attribute = failed_attributes.first
      failed_attributes.empty?
    end
  end
  
  def protect_attributes(attributes)
    ProtectAttributes.new(attributes)
  end
  
  def protect_attribute(attribute)
    ProtectAttributes.new(*[attribute])
  end
end

Api key (or any kind of key) generator

Generates a random key for API neatness.

class KeyGenerator
  require "digest/sha1"
  def self.generate(length = 10)
    Digest::SHA1.hexdigest(Time.now.to_s + rand(12341234).to_s)[1..length]
  end
end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS