Skip to content

Instantly share code, notes, and snippets.

@mikebaldry
Created September 21, 2011 12:46
Show Gist options
  • Select an option

  • Save mikebaldry/1231938 to your computer and use it in GitHub Desktop.

Select an option

Save mikebaldry/1231938 to your computer and use it in GitHub Desktop.
view:
= f.inputs :name => "Contract details", :class => "accordion" do
= f.input :mpan
= f.input :kva
= f.input :voltage, :as => :radio, :collection => {"Low" => "LV", "High" => "HV"}
= f.input :estimated_annual_consumption
model:
class ElectricityContract < Contract (MogngoMapper::EmbeddedDocument)
plugin Joint
key :mpan, Mpan # this guy!
key :kva, Integer
key :estimated_annual_consumption, Integer
key :voltage, String
attachment :half_hourly_data
end
Mpan class :
class Mpan
attr_reader :profile, :mts, :llf, :did, :uid, :cd
def initialize(profile, mts, llf, did, uid, cd)
raise "Profile invalid" unless profile.length == 2
raise "Meter time-switch code invalid" unless mts.length == 3
raise "Line-loss factor invalid" unless llf.length == 3
raise "Distributor id invalid" unless did.length == 2
raise "Unique identifier invalid" unless uid.length == 8
core = did + uid + cd
primes = [3, 5, 7, 13, 17, 19, 23, 29, 31, 37, 41, 43]
check_digit = (0..11).inject(0) { |sum, n| sum + (core[n, 1].to_i * primes[n]) } % 11 % 10
raise "Check digit invalid" unless check_digit == cd[-1, 1].to_i
@profile = profile
@mts = mts
@llf = llf
@did = did
@uid = uid
@cd = cd
end
def top_line
@profile + @mts + @llf
end
def bottom_line
@did + @uid + @cd
end
def to_s
"#{top_line} / #{bottom_line}"
end
def self.to_mongo(value)
return {:profile => value.profile, :mts => value.mts, :llf => value.llf, :did => value.did, :uid => value.uid, :cd => value.cd} if value.is_a? Mpan
value.nil? ? nil : {:profile => value["profile"], :mts => value["mts"], :llf => value["llf"], :did => value["did"], :uid => value["uid"], :cd => value["cd"]}
end
def self.from_mongo(value)
return value if value.is_a? Mpan
value.nil? ? nil : Mpan.new(value[:profile], value[:mts], value[:llf], value[:did], value[:uid], value[:cd])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment