Sha256: b5e25da4a25963f7a835c72c2ddb01d001997cc7f942ecd36ba7358f074d0e8e

Contents?: true

Size: 1.96 KB

Versions: 4

Compression:

Stored size: 1.96 KB

Contents

require 'rails3_artifactor'
require 'logging_assist'

module ActiveRecord 
  module Generators
    class RolesGenerator < Rails::Generators::NamedBase      
      desc "Add role strategy to a model" 
      
      class_option :strategy, :type => :string, :aliases => "-s", :default => 'role_string', 
                   :desc => "Role strategy to use (admin_flag, role_string, roles_string, role_strings, one_role, many_roles, roles_mask)"


      class_option :roles, :type => :array, :aliases => "-r", :default => [], :desc => "Valid roles"

      class_option :default_roles, :type => :boolean, :default => true, :desc => "Use default roles :admin and :base"


      def apply_role_strategy
        log.add_logfile
        log.debug "apply_role_strategy for : #{strategy} in model #{name}"
        begin
          insert_into_model name do
            insertion_text
          end
        rescue
          say "Model #{name} not found"
        end
      end 
      
      protected                  

      extend Rails3::Assist::UseMacro
      use_orm :active_record
      include Rails::Assist::BasicLogging

      def orm
        :active_record
      end
  
      def default_roles
        options[:default_roles] ? [:admin, :guest] : []        
      end
  
      def roles_to_add
        @roles_to_add ||= default_roles.concat(options[:roles]).to_symbols.uniq
      end
  
      def roles        
        roles_to_add.map{|r| ":#{r}" }
      end
  
      def role_strategy_statement 
        "strategy :#{strategy}, :default\n#{role_class_stmt}"
      end

      def role_class_stmt
        "  role_class :role" if [:one_role, :many_roles].include? (strategy.to_sym)
      end
  
      def roles_statement
        roles ? "valid_roles_are #{roles.join(', ')}" : ''
      end
  
      def insertion_text
        %Q{include Roles::#{orm.to_s.camelize} 
  #{role_strategy_statement}
  #{roles_statement}}
      end
  
      def strategy
        options[:strategy]                
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
roles_active_record-0.2.3 lib/generators/active_record/roles/roles_generator.rb
roles_active_record-0.2.2 lib/generators/active_record/roles/roles_generator.rb
roles_active_record-0.2.1 lib/generators/active_record/roles/roles_generator.rb
roles_active_record-0.2.0 lib/generators/active_record/roles/roles_generator.rb