sample.rb 1.77 KB
Newer Older
Sara Kuqi's avatar
fc  
Sara Kuqi committed
1
class Sample < ApplicationRecord
Sara Kuqi's avatar
Sara Kuqi committed
2
  attr_reader :formul
3
  attr_accessor :mw
Sara Kuqi's avatar
Sara Kuqi committed
4

Sara Kuqi's avatar
Sara Kuqi committed
5
6
  has_many :results
  accepts_nested_attributes_for :results,  :reject_if => :all_blank, :allow_destroy => true
Sara Kuqi's avatar
fc  
Sara Kuqi committed
7
8
9
  belongs_to :user
  validates :user_id, presence: true
  validates :name, presence: true, length: { maximum: 50 }
chia-lin.lin's avatar
chia-lin.lin committed
10
  validates :formula, length: { maximum: 140 }
Sara Kuqi's avatar
fc  
Sara Kuqi committed
11
  validates :status, presence: true, length: { maximum: 140 }
Sara Kuqi's avatar
Sara Kuqi committed
12
  before_save :calculate_percentage
ira.maier's avatar
changes    
ira.maier committed
13
  has_many_attached :files
Sara Kuqi's avatar
Sara Kuqi committed
14

Sara Kuqi's avatar
Sara Kuqi committed
15
16
17
18
  default_scope do
    order("CASE WHEN status='submitted' THEN 0 ELSE 1 END").order(updated_at: :desc)
  end

Sara Kuqi's avatar
Sara Kuqi committed
19
  include MolApp::PeriodicTable
pei-chi.huang's avatar
pei-chi.huang committed
20
  PREDEF_ELEMENTS = %w(N C H S)
Sara Kuqi's avatar
Sara Kuqi committed
21
22
23

  REG = /(#{ELEMENTS.keys.map(&:to_s).sort.reverse.join("|")})(\d*)/

chia-lin.lin's avatar
chia-lin.lin committed
24
25
26
27
  def operator_link_id
    User.find_by(name: operator_name)&.id
  end

Sara Kuqi's avatar
Sara Kuqi committed
28
29
30
31
32
33
34
35
36
37
  def formatted_calculation
    self.calculation
    keys = ( PREDEF_ELEMENTS+(self.calculation.keys  - PREDEF_ELEMENTS) ).uniq
    result = {}
    keys.each do |key|
      result[key] = self.calculation[key] || 0
    end

    result
  end
Sara Kuqi's avatar
Sara Kuqi committed
38

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  def parse_formula
   left_over = formula
   @formul={}
   while !left_over.blank?
     left_over.match(REG)
     return false unless $1
     left_over = $'
     if $2 == ""
       then  value = 1
     else
       value = $2.to_i
     end
     @formul[$1] = value
   end
   @formul
Sara Kuqi's avatar
Sara Kuqi committed
54
55
  end

Sara Kuqi's avatar
Sara Kuqi committed
56
57
58
  def calculate_mw
    @mw=0
    @formul.each_pair do |key, value|
59
60
61
62
      puts "#{key} is #{value}"
      @mw += get_atomic_weight(key)*value
    end
    @mw
Sara Kuqi's avatar
Sara Kuqi committed
63
64
  end

65
66
67
68
69
70
71
72
73
  def calculate_percentage
    @expected_result={}
    unless parse_formula
      errors.add('Warning','Formula is not valid')
      throw(:abort)
    end
    calculate_mw
    @formul.each_pair{|k,v|  @expected_result[k]=((v*get_atomic_weight(k)/@mw)*100).to_f}
    assign_attributes(calculation: @expected_result)
Sara Kuqi's avatar
Sara Kuqi committed
74
  end
Sara Kuqi's avatar
fc  
Sara Kuqi committed
75
end