Module: Cream::MigrationHelper::CodeRefactor

Defined in:
lib/generators/cream_refactor.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to_roleObject



46
47
48
# File 'lib/generators/cream_refactor.rb', line 46

def belongs_to_role
  'belongs_to :role'
end

#belongs_to_userObject



42
43
44
# File 'lib/generators/cream_refactor.rb', line 42

def belongs_to_user
  'belongs_to :user'
end

#clear_relations(model_name) ⇒ Object

erase



6
7
8
9
10
11
# File 'lib/generators/cream_refactor.rb', line 6

def clear_relations(model_name)       
  model_name = model_name.to_s
  erase_in(model_name, has_roles_through_assignments)
  erase_in(model_name, has_roles)  
  erase_in(model_name, has_role_assignments)
end

#erase_in(model_name, txt) ⇒ Object



13
14
15
16
17
18
# File 'lib/generators/cream_refactor.rb', line 13

def erase_in(model_name, txt)      
  model_name = model_name.to_s   
  file = File.new(model_file(model_name))
  return if !(file.read =~ /#{txt}/)         
  gsub_file model_file(model_name), /#{Regexp.escape(txt + "\n")}/, ''
end

#has_role_assignmentsObject

refactor code



51
52
53
# File 'lib/generators/cream_refactor.rb', line 51

def has_role_assignments 
  'has_many :role_assignments'
end

#has_rolesObject



59
60
61
# File 'lib/generators/cream_refactor.rb', line 59

def has_roles 
  'has_many :roles'
end

#has_roles_through_assignmentsObject



55
56
57
# File 'lib/generators/cream_refactor.rb', line 55

def has_roles_through_assignments 
  'has_many :roles, :through => :role_assignments'
end

#insert_relation(model_name, relation) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/generators/cream_refactor.rb', line 29

def insert_relation(model_name, relation)
  model_name = model_name.to_s
  file = File.new(model_file(model_name))
  return if (file.read =~ /#{relation}/) 
  gsub_file model_file(model_name), /class #{model.camelize} < ActiveRecord::Base/ do |match|
    match << "\n  #{relation}"
  end
end

#remove_relation(model_name, relation) ⇒ Object



38
39
40
# File 'lib/generators/cream_refactor.rb', line 38

def remove_relation(model_name, relation)
  erase_in(model_name.to_s, relation)  
end

#role_assignment_file_contentObject



72
73
74
75
76
77
78
79
# File 'lib/generators/cream_refactor.rb', line 72

def role_assignment_file_content
  %Q{
  class RoleAssignment < ActiveRecord::Base
#{belongs_to_user}
#{belongs_to_role}
  end          
  }
end

#role_file_contentObject



63
64
65
66
67
68
69
70
# File 'lib/generators/cream_refactor.rb', line 63

def role_file_content
  %Q{
  class Role < ActiveRecord::Base
  #{has_role_assignments}
  #{has_roles_through_assignments}
  end          
  }    
end

#write_model_file(model_name, content) ⇒ Object

insert



22
23
24
25
26
27
# File 'lib/generators/cream_refactor.rb', line 22

def write_model_file(model_name, content)    
  model_name = model_name.to_s
  File.open(model_file(model_name), 'w+') do |f| 
    f.write(content) 
  end
end