money_oleole7177 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e0b6c9b1ee3793f6b1c217cc9c150b02c83730f5
4
+ data.tar.gz: 0f4b03bb61900e2979eb52a2a7ac7b9b787cef42
5
+ SHA512:
6
+ metadata.gz: 6f5d8f118c5f8ca879c0ddbeeb0f858e69371be3d4422ac2c758df1e6357dae6782e90c675650a3c00ede4beed21bbba532c899b2e5134c6a52aab16ddd018b0
7
+ data.tar.gz: 0f14835e6aea100a704eab7364e8e6e67dd424d419ee4d222a97712e8606acea632e5d9b4be731d6fbc07daa6dc8ac0ae4cab1d2db266ab78f679b0078e0ba39
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.bundle
11
+ *.so
12
+ *.o
13
+ *.a
14
+ mkmf.log
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format documentation
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in money.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2015 OleOle7177
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # Money
2
+
3
+ Гем для работы с курсами валют.
4
+
5
+ ## Установка
6
+
7
+ Добавьте следующую строку в Gemfile вашего приложения:
8
+
9
+ ```ruby
10
+ gem 'money', git: 'https://github.com/OleOle7177/money'
11
+ ```
12
+ Зависимости гема:
13
+
14
+ ```ruby
15
+ gem 'nokogiri'
16
+ gem 'rspec' #для тестов
17
+ ```
18
+ Затем запустите bundle:
19
+
20
+ $ bundle install
21
+
22
+ Далее добавьте в свой проект миграции базы данных и модели ActiveRecord:
23
+
24
+ $ rails g money:install
25
+
26
+ Запустите миграции:
27
+
28
+ $ rake db:migrate
29
+
30
+ Гем готов к работе!
31
+
32
+ ## Использование
33
+
34
+ Гем предоставляет следующий интерфейс для работы с курсами валют:
35
+
36
+ 1) Установить базовую валюту с кодом 'EUR' для кросс-конвертаций:
37
+ ```ruby
38
+ Money.set_base('EUR')
39
+ ```
40
+ 2) Узнать текущую базовую валюту:
41
+ ```ruby
42
+ Money.get_base
43
+ ```
44
+ 3) Для валюты с кодом 'USD' установить курс со значением 1.5 относительно базовой:
45
+ ```ruby
46
+ Money.set_currency(from: 'USD', rate: 1.5)
47
+ ```
48
+ 4) Узнать курс валюты с кодом 'USD' относительно базовой на текущий момент:
49
+ ```ruby
50
+ Money.get_currency(from: 'USD')
51
+ ```
52
+ 5) Узнать курс валюты с кодом 'USD' относительно базовой на момент 7 марта 2015 года 12:00:00:
53
+ ```ruby
54
+ Money.get_currency(from: 'USD', datetime: '2015-03-07 12:00:00')
55
+ ```
56
+ 6) Узнать курс валюты 'USD' относительно валюты 'EUR' на текущий момент:
57
+ ```ruby
58
+ Money.get_currency(from: 'USD', to: 'EUR')
59
+ ```
60
+ 7) Узнать курс валюты 'USD' относительно валюты 'EUR' на момент 7 марта 2015 года 12:00:00:
61
+ ```ruby
62
+ Money.get_currency(from: 'USD', to: 'EUR', datetime: '2015-03-07 12:00:00')
63
+ ```
64
+ 8) Получить значения курсов валют относительно рубля с сервиса Центробанка РФ (для валют, занесённых в базу данных):
65
+
66
+ $ rake getcbrates
67
+
68
+ 9) Рассчитать значения курсов валют (на основе данных ЦБ РФ о курсах относительно рубля) относительно текущей базовой валюты:
69
+ ```ruby
70
+ Money.calculate
71
+ ```
72
+
73
+
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
@@ -0,0 +1,40 @@
1
+ #lib/generators/gemname/install_generator.rb
2
+ require 'rails/generators'
3
+ require 'rails/generators/migration'
4
+ require 'rails/generators/active_record'
5
+
6
+ module Money
7
+ class InstallGenerator < Rails::Generators::Base
8
+ include Rails::Generators::Migration
9
+
10
+ source_root File.expand_path("../templates", __FILE__)
11
+
12
+ desc "Copy migrations, models and tasks to application"
13
+
14
+ def self.next_migration_number(path)
15
+ ActiveRecord::Generators::Base.next_migration_number(path)
16
+ end
17
+
18
+
19
+ def copy_midrations
20
+ migration_template "migrations/create_currency.rb", "db/migrate/create_currency.rb"
21
+ migration_template "migrations/create_exchange_rate.rb", "db/migrate/create_exchange_rate.rb"
22
+ migration_template "migrations/create_calculated_exchange_rate.rb", "db/migrate/create_calculated_exchange_rate.rb"
23
+ end
24
+
25
+ def copy_models
26
+ template "models/currency.rb", "app/models/currency.rb"
27
+ template "models/exchange_rate.rb", "app/models/exchange_rate.rb"
28
+ template "models/calculated_exchange_rate.rb", "app/models/calculated_exchange_rate.rb"
29
+ end
30
+
31
+ def copy_tasks
32
+ template "tasks/getcbrates.rake", "lib/tasks/getcbrates.rake"
33
+ end
34
+
35
+
36
+ # Generator Code. Remember this is just suped-up Thor so methods are executed in order
37
+
38
+
39
+ end
40
+ end
@@ -0,0 +1,14 @@
1
+ class CreateCalculatedExchangeRate < ActiveRecord::Migration
2
+ def change
3
+ create_table :calculated_exchange_rates do |t|
4
+ t.integer :from_currency_id
5
+ t.integer :to_currency_id
6
+ t.float :rate
7
+
8
+ t.datetime :created_at
9
+ t.string :created_by
10
+ end
11
+
12
+ add_index :calculated_exchange_rates, [:from_currency_id, :created_at], unique: true, name: 'index_on_calculated_rate'
13
+ end
14
+ end
@@ -0,0 +1,15 @@
1
+ class CreateCurrency < ActiveRecord::Migration
2
+ def change
3
+ create_table :currencies do |t|
4
+ t.string :name
5
+ t.string :code
6
+ t.string :symbol
7
+ t.boolean :is_base, default: false
8
+
9
+ t.timestamps
10
+ end
11
+
12
+ add_index :currencies, :is_base
13
+ add_index :currencies, :code, unique: true
14
+ end
15
+ end
@@ -0,0 +1,12 @@
1
+ class CreateExchangeRate < ActiveRecord::Migration
2
+ def change
3
+ create_table :exchange_rates do |t|
4
+ t.integer :currency_id
5
+ t.float :rate
6
+
7
+ t.datetime :created_at
8
+ end
9
+
10
+ add_index :exchange_rates, [:currency_id, :created_at], unique: true
11
+ end
12
+ end
@@ -0,0 +1,3 @@
1
+ class CalculatedExchangeRate < ActiveRecord::Base
2
+ validates :from_currency_id, :to_currency_id, :rate, presence: true
3
+ end
@@ -0,0 +1,11 @@
1
+ class Currency < ActiveRecord::Base
2
+ has_many :exchange_rates
3
+ before_save :check_is_base
4
+
5
+ validates :name, :code, :symbol, presence: true
6
+ validates :code, :symbol, uniqueness: true
7
+
8
+ def check_is_base
9
+ self.class.where('id != ? and is_base == ?', id, true).update_all(is_base: false) if is_base
10
+ end
11
+ end
@@ -0,0 +1,5 @@
1
+ class ExchangeRate < ActiveRecord::Base
2
+ belongs_to :currency
3
+
4
+ validates :currency_id, :rate, presence: true
5
+ end
@@ -0,0 +1,17 @@
1
+ task :getcbrates => :environment do
2
+ require 'open-uri'
3
+ # get the XML data form CB URL
4
+ file_handle = open('http://www.cbr.ru/scripts/XML_daily.asp')
5
+
6
+ # get document xml string and create Nokogiri object
7
+ doc = Nokogiri::XML(file_handle)
8
+
9
+ @curriencies = Currency.all
10
+
11
+ doc.css("Valute").each do |valute|
12
+ @currency = @curriencies.find{|i| i.code == valute.css('CharCode').text}
13
+ ExchangeRate.create(currency: @currency, rate: valute.css('Value').text.gsub(',', '.').to_f) unless @currency.nil?
14
+ end
15
+
16
+ Money.calculate
17
+ end
@@ -0,0 +1,3 @@
1
+ module Money
2
+ VERSION = "0.0.3"
3
+ end
data/lib/money.rb ADDED
@@ -0,0 +1,46 @@
1
+ module Money
2
+
3
+ def self.get_base
4
+ Currency.find_by_is_base(true).code
5
+ end
6
+
7
+ def self.set_base(sym)
8
+ currency = Currency.find_by_code(sym)
9
+ unless (currency.nil? || get_base == sym)
10
+ currency.is_base = true
11
+ currency.save
12
+ end
13
+ end
14
+
15
+ def self.set_currency(options = {})
16
+ from = Currency.find_by_code(options[:from])
17
+ to = Currency.find_by_is_base(true)
18
+ rate = options[:rate]
19
+ CalculatedExchangeRate.create(from_currency_id: from.id, to_currency_id: to.id, rate: rate) unless from.id == to.id
20
+ end
21
+
22
+ def self.calculate
23
+ base = Currency.find_by_is_base(true)
24
+ cur_base = base.exchange_rates.last
25
+ @curriencies = Currency.all.includes(:exchange_rates)
26
+ @curriencies.each do |cur|
27
+ cur_from = cur.exchange_rates.last
28
+ set_currency(from: cur.code, rate: (cur_from.rate/cur_base.rate).to_f.round(4))
29
+ end
30
+ end
31
+
32
+ def self.get_currency(options={})
33
+ from = Currency.find_by_code(options[:from])
34
+ to = options[:to] ? Currency.find_by_code(options[:to]) : Currency.find_by_is_base(true)
35
+ datetime = options[:datetime] ? options[:datetime] : DateTime.now
36
+
37
+ unless from.id == to.id
38
+ currencyfrom = CalculatedExchangeRate.where("from_currency_id = ? and created_at < ?", from.id, datetime).last
39
+ currencyto = CalculatedExchangeRate.where("from_currency_id = ? and created_at < ?", to.id, datetime).last
40
+ (currencyfrom.rate/currencyto.rate).to_f.round(4)
41
+ else
42
+ 1.0
43
+ end
44
+ end
45
+ end
46
+
data/money-0.0.2.gem ADDED
Binary file
data/money.gemspec ADDED
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'money/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "money_oleole7177"
8
+ spec.version = Money::VERSION
9
+ spec.authors = ["OleOle7177"]
10
+ spec.email = ["ole_@bk.ru"]
11
+ spec.summary = %q{Гем для конвертации курсов валют}
12
+ spec.description = %q{Гем использует данные ЦБ РФ}
13
+ spec.homepage = ""
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.7"
22
+ spec.add_development_dependency "rake", "~> 10.0"
23
+ spec.add_development_dependency "rspec"
24
+ spec.add_development_dependency "nokogiri"
25
+ end
@@ -0,0 +1,52 @@
1
+ require 'spec_helper'
2
+ require 'rake'
3
+
4
+ describe Money do
5
+
6
+ before(:all) do
7
+ Currency.find_or_create_by(name: "US Dollar", code: "USD", is_base: true, symbol: "$")
8
+ Currency.find_or_create_by(name: "Euro", code: "EUR", is_base: false, symbol: "E")
9
+ Currency.find_or_create_by(name: "English", code: "GBP", is_base: false, symbol: "R")
10
+ end
11
+
12
+ after(:all) do
13
+ Currency.destroy_all
14
+ CalculatedExchangeRate.destroy_all
15
+ ExchangeRate.destroy_all
16
+ end
17
+
18
+ it "get_base returns base valute" do
19
+ expect(Money.get_base).to eq('USD')
20
+ end
21
+
22
+ it "set_base sets base valute" do
23
+ Money.set_base('EUR')
24
+ expect(Money.get_base).to eq('EUR')
25
+ end
26
+
27
+ it "rake task gets rates for all curriencies" do
28
+ expect { load File.expand_path("../../../lib/tasks/getcbrates.rake", __FILE__)
29
+ Rake::Task.define_task(:environment)
30
+ Rake::Task["getcbrates"].invoke}.to change {ExchangeRate.count}.by(3)
31
+ end
32
+
33
+ it "calculate calculates curriences for all valutes" do
34
+ expect { Money.calculate }.to change {CalculatedExchangeRate.count}.by(2)
35
+ end
36
+
37
+ it "get_currency works correct" do
38
+ expect(Money.get_currency(from: 'EUR')).to eq(1.0)
39
+ end
40
+
41
+ it "set and get currency_works correct" do
42
+ Money.set_base('EUR')
43
+ Money.set_currency(from: 'USD', rate: 2.0)
44
+ Money.set_currency(from: 'GBP', rate: 0.5)
45
+ expect(Money.get_currency(from: 'USD', to: 'GBP')).to eq(4.0)
46
+ end
47
+
48
+ it "database doesn't have valute rate to itself" do
49
+ expect(CalculatedExchangeRate.where("from_currency_id == to_currency_id").count).to eq(0)
50
+ end
51
+
52
+ end
@@ -0,0 +1,8 @@
1
+ require 'bundler/setup'
2
+ Bundler.setup
3
+
4
+ require 'money' # and any other gems you need
5
+
6
+ RSpec.configure do |config|
7
+ # some (optional) config here
8
+ end
metadata ADDED
@@ -0,0 +1,122 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: money_oleole7177
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.3
5
+ platform: ruby
6
+ authors:
7
+ - OleOle7177
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-03-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.7'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: nokogiri
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: "Гем использует данные ЦБ РФ"
70
+ email:
71
+ - ole_@bk.ru
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - Gemfile
79
+ - LICENSE.txt
80
+ - README.md
81
+ - Rakefile
82
+ - lib/generators/money/install_generator.rb
83
+ - lib/generators/money/templates/migrations/create_calculated_exchange_rate.rb
84
+ - lib/generators/money/templates/migrations/create_currency.rb
85
+ - lib/generators/money/templates/migrations/create_exchange_rate.rb
86
+ - lib/generators/money/templates/models/calculated_exchange_rate.rb
87
+ - lib/generators/money/templates/models/currency.rb
88
+ - lib/generators/money/templates/models/exchange_rate.rb
89
+ - lib/generators/money/templates/tasks/getcbrates.rake
90
+ - lib/money.rb
91
+ - lib/money/version.rb
92
+ - money-0.0.2.gem
93
+ - money.gemspec
94
+ - spec/features/money_spec.rb
95
+ - spec/spec_helper.rb
96
+ homepage: ''
97
+ licenses:
98
+ - MIT
99
+ metadata: {}
100
+ post_install_message:
101
+ rdoc_options: []
102
+ require_paths:
103
+ - lib
104
+ required_ruby_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ required_rubygems_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubyforge_project:
116
+ rubygems_version: 2.2.2
117
+ signing_key:
118
+ specification_version: 4
119
+ summary: "Гем для конвертации курсов валют"
120
+ test_files:
121
+ - spec/features/money_spec.rb
122
+ - spec/spec_helper.rb