text stringlengths 10 2.61M |
|---|
require 'spec_helper'
describe Question do
it 'can create a new question' do
question = Question.new(question: 'Feeling', long_form: 'How do you feel?')
expect(question).to be_valid
end
it 'has a valid factory' do
expect(FactoryGirl.create(:question)).to be_valid
end
it 'is not valid without a question' do
expect(Question.new(question: nil)).to_not be_valid
end
it 'is not valid without a long form' do
expect(Question.new(long_form: nil)).to_not be_valid
end
end
|
# This class is linked to the lessons table
class Lesson < ApplicationRecord
# 1 cour - N lessons
belongs_to :cour
end
|
require 'rubygems'
require 'mechanize'
class Agent
def initialize(product_name)
@agent = Mechanize.new
@product_name = product_name
@@index = 'http://google.fr'
end
# go into the search page and enter the product name and submit
# this function returns the search result page.
def go_to_search(search_form_id, search_bar_name)
search_form = @agent.get(@@index).form_with(search_form_id)
search_form[search_bar_name] = @product_name
page = @agent.submit(search_form)
end
# cheapest product = [name,href,price]
def compare_with_cheapest_product(product_name, href, price)
if defined? @cheapest_prodcut
cheapest_price = @cheapest_prodcut[-1]
@cheapest_prodcut = [product_name,href,price] if price < cheapest_price
else
@cheapest_prodcut = [product_name,href,price]
end
end
end |
require 'date'
require 'open-uri'
require 'csv'
require 'cgi'
require_relative 'constants'
module Util
module_function
def cpubdate_to_timestamp(cpubdate)
return '' if cpubdate.nil? || cpubdate.empty?
date = cpubdate.gsub(/oktober/i, 'October') # hack for missing Oktober
date = Date.parse(date)
"#{date.strftime('%Y-%m-%d')} 12:00:00"
end
def timestamp_to_pubDate(timestamp)
pubDate = {
year: timestamp[0..3].to_i,
month: timestamp[5..6].to_i,
day: timestamp[8..9].to_i,
time: timestamp[11..-1]
}
pubDate[:date] = Date.new(pubDate[:year], pubDate[:month], pubDate[:day])
"#{pubDate[:date].strftime('%a, %d %b %Y')} #{pubDate[:time]} +0000"
end
def excerpt(text, max_characters = 160)
return '' unless text.respond_to?(:gsub, :split)
# Clean partial sentences ending in ...
text = text.gsub(/(\.|\?|!)\s+.*?\.\.\.\z/, '\1')
# Convert line breaks to spaces (adding punctuation if missing)
text = text.gsub(/(\w)\s*[\n\r]+\s*/, '\1. ')
text = text.gsub(/\s{2,}/, ' ')
text = text.gsub(/\A\s*/, '')
text = text.split(/([?.!])/)
excerpt_text = ''
text.each do |sentence|
next if sentence.empty?
if excerpt_text.length + sentence.length < max_characters
excerpt_text += sentence
else
return excerpt_text.empty? ? text.first : excerpt_text
end
end
excerpt_text
end
def serialize(data_fields)
serialized = "a:#{data_fields.size}:{"
data_fields.each_with_index do |data_field, index|
serialized += "i:#{index};"
serialized += "a:#{data_field.size}:{"
data_field.each do |key, val|
serialized += "s:#{serialize_count(key)}:\"#{key}\";"
serialized += "s:#{serialize_count(val)}:\"#{val}\";"
end
serialized += "}"
end
serialized += "}"
end
def serialize_count(string)
string.length +
string.gsub(/[\w \.\+\/\$\(\):%\-,<>]/, '').length
end
def download_images_from_csv(country_code, limit = nil)
col = {}
CSV.foreach("metadata_files/#{country_code}.csv").with_index do |row, index|
if col.empty?
row.each_with_index do |header, col_index|
col[header] = col_index
end
return if col[Constants::KEYS[:image]].nil?
next
end
# Allow force exit early for tests
return if limit == index - 1
# Ignore non-Uberflip images
next unless uberflip_image?(row[col[Constants::KEYS[:image]]])
post_type = post_type_empty?(row, col) ? 'post' : row[col[Constants::KEYS[:type]]]
download_image(
row[col[Constants::KEYS[:image]]],
country_code,
"#{country_code}-#{post_type}-#{row[col[Constants::KEYS[:id]]]}"
)
end # end CSV.foreach
end
def post_content_images(post_content, post_id, country_code)
images = post_content.scan(Constants::UBERFLIP_CDN_IMAGE_REGEXP)
images.each_with_index do |image, index|
suffix = image_suffix(image)
new_image_name = "#{country_code}-#{post_id}-#{index}"
download_image(image, country_code, new_image_name)
post_content.gsub!(image, "#{Constants::MIGRATED_IMAGES_DIR}#{country_code}/#{new_image_name}.#{suffix}")
end
post_content
end
def handle_resource(item)
return item unless item[Constants::KEYS[:type]].eql?('resource')
if item[Constants::KEYS[:url]].match(/\Ahttps:\/\/[\w\.]+\/self-service/)
item['resource-type'] = Constants::RESOURCE_TYPES[:video]
item['item_tags'] += Constants::LIBRARY_VIDEO_TAGS
else
item['resource-type'] = Constants::RESOURCE_TYPES[:whitepaper]
end
item
end
def get_post_type(url)
slugs = url.scan(/\Ahttps?:\/\/[a-z\.\-]+\/(.+?)\//)
return if slugs.empty?
Constants::POST_TYPES[slugs.first.first]
end
def post_type_empty?(row, col)
col[Constants::KEYS[:type]].nil? ||
row[col[Constants::KEYS[:type]]].nil? ||
row[col[Constants::KEYS[:type]]].empty?
end
def download_image(url, subdir, new_filename = '')
suffix = image_suffix(url)
return false if suffix.empty?
begin
puts "Downloading #{url}"
web_image = open(url)
rescue OpenURI::HTTPError => http_error
puts http_error
return false
end
image_file_path = "images/#{subdir}/#{new_filename}.#{suffix}"
IO.copy_stream(web_image, image_file_path)
end
def uberflip_image?(image_url)
return false if image_url.nil?
image_url.match(Constants::UBERFLIP_CDN)
end
def image_suffix(image)
begin
web_image = open(image)
return Constants::CONTENT_TYPE_SUFFIXES[web_image.content_type] || 'gif'
rescue OpenURI::HTTPError => http_error
puts http_error
end
''
end
def clean_url(url)
CGI.escape(url).gsub('%2F', '/').gsub('%3A', ':')
end
end
|
# -*- encoding : utf-8 -*-
class Cms::HolesController < Cms::BaseController
before_action :find_group, only: [:new, :create]
def index
@holes = Hole.page(params[:page])
end
def show
@hole = Hole.find(params[:id])
end
def new
@hole = Hole.new
end
def edit
@hole = Hole.find(params[:id])
end
def create
@hole = Hole.new(hole_params)
if @hole.save
redirect_to [:cms, @hole], notice: '球洞创建成功!'
else
render action: 'new'
end
end
def update
@hole = Hole.find(params[:id])
if @hole.update_attributes(hole_params)
redirect_to [:cms, @hole.course.venue], notice: '球洞更新成功!'
else
render action: 'edit'
end
end
def destroy
@hole = Hole.find(params[:id])
@hole.trash
redirect_to cms_holes_path, notice: '删除成功!'
end
def update_par
hole = Hole.find(params[:id])
if hole.update(par: params[:value])
render json: { success: true, message: hole.par }
else
render json: { success: false, message: '格式不正确,请重新输入!' }
end
end
protected
def find_group
@group = Group.find(params[:group_id])
end
def hole_params
params.require(:hole).permit!
end
end
|
require "application_system_test_case"
class MessagesTest < ApplicationSystemTestCase
setup do
@message = messages(:message_simple)
end
test "visiting the index" do
_login()
visit messages_url
assert_selector "h1", text: "Messages"
end
test "creating a Message" do
_login()
visit messages_url
click_on "New Message"
fill_in "Content", with: @message.content
page.select @message.dest.name, from: "Dest"
check "Is public" if @message.is_public
click_on "Create Message"
assert_text "Message was successfully created"
click_on "Back"
end
test "reply to a Message" do
_login(:user_f2)
visit messages_url
click_on "Show", match: :first
click_on "Reply", match: :first
fill_in "Content", with: "Reply"
click_on "Reply"
assert_text "Message was successfully created"
click_on "Back"
end
test "destroying a Message" do
_login(:user_f1)
visit messages_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Message was successfully destroyed"
end
private
def _login(user_fixture = :user_f1)
# log in user session ...
@user = users(user_fixture)
visit login_url(:html)
fill_in "Email", with: @user.email
fill_in "Password", with: "test"
click_on "Log in", { class: "btn" }
end
end
|
require 'pathname'
##
# Functionality for dealing with Sass (scss, sass) files.
#TODO: Restructure as instance.
class Sass
attr_accessor :files
def initialize(files, directory)
@files = files
@directory = directory
end
def self.[](dir=".")
throw Exception.new("Expected a dir, got file #{ dir } in Sass[]!") if File.file? dir
throw Exception.new("Nonexistant #{ dir } in Sass[]!") if (not File.exist? dir)
Sass.new(Dir["**/*.{sass,scss}", base: dir], dir)
end
##
# Checks if a +file+ is a css file.
# Params:
# +file+:: a filename or filepath string.
def self.is_css?(file)
/\.css\z/.match?(file)
end
##
# Checks if a +file+ is a sass file. A sass file is defined as a file ending
# in either sass or scss.
# Params:
# +file+:: a filename or filepath string.
def self.is_sass?(file)
/\.s(a|c)ss\z/.match?(file)
end
##
# Checks if a +file+ is a sass mixin. Mixins are defined as files that start
# with a "_" and end in either .sass or .scss.
# Params:
# +file+:: a filename or filepath string.
def self.is_mixin?(file)
/\A(.*\/)?_.*\.s(a|c)ss\z/.match?(file)
end
##
# Call the SASS transpiler on the +input_file+. Outputs a css file if successful. Will
# return the filepath of the transpiled css file.
# Params:
# +input_file+:: a filepath string, evaluated relative to the cwd.
def self.call_sass(input_file, out_dir=nil)
raise Exception.new("Could not find #{ input_file } in Sass.call_sass!") if (not File.exist?(input_file))
basename = File.basename input_file
dirname = File.dirname input_file
out_dir = out_dir ? out_dir : dirname
output_file = File.join(out_dir, basename.sub(/\.[a-zA-Z0-9]+\z/, ".css"))
%x{sass --no-source-map #{input_file} #{output_file}}
p "Sass compiled #{ input_file } -> #{ output_file }"
Sass.sanitize_paths(output_file)
end
##
# Call the SASS transpiler on the instance's +@files+. Returns a list of paths
# representing the transpiled css files.
# Params:
# +out+:: A directory path.
def render(out: @directory)
@files.each_with_object([]) do |f, result|
local_dir = File.dirname f
full_path = File.realpath(f, @directory)
out_path = File.join(out, local_dir)
if sass_and_not_mixin? full_path
converted_file = Sass.call_sass(full_path, out_path)
result << converted_file
else
next
end
end
end
private
def self.sanitize_paths(path)
path.gsub(/\/\.\//, "/")
end
def sass_and_not_mixin?(path)
File.file?(path) && Sass.is_sass?(path) && (not Sass.is_mixin?(path))
end
end
|
class RemoveUsernameEmployeeTable < ActiveRecord::Migration
def up
remove_column :users, :username
end
def down
add_column :users, :username, :string, :limit => 24
end
end
|
require 'spec_helper'
describe "Discussion API", type: :api do
let(:user) { build(:logged_user) }
let!(:account) { create(:account_with_schema, subdomain: ApiHelper::SUBDOMAIN, owner: user) }
before :each do
set_header user
end
describe "GET /discussions" do
it "should render 404 if no targetable neither user are provided" do
get "/discussions", format: :json
expect(last_response.status).to eq(404)
end
describe "when asking for a targetable" do
let!(:project) { create_on_schema :project, account.subdomain }
it "should return empty discussions" do
get "/discussions?targetable_id=#{project.id}&targetable_type=Project", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body).count).to eq(0)
end
it "should return one discussion" do
on_schema account.subdomain do
discussion = build(:discussion)
discussion.build_targets_from_targetable project
discussion.save!
end
get "/discussions?targetable_id=#{project.id}&targetable_type=Project", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body).count).to eq(1)
end
it "should return two discussions" do
on_schema account.subdomain do
task = build(:task_with_users_and_project, taskable_id: project.id, taskable_type: 'Project')
task.save!
discussion = build(:discussion)
discussion.build_targets_from_targetable task
discussion.save!
discussion2 = build(:discussion, content: 'TESSSSTTTTTIIIINNNG', title: 'Test2')
discussion2.build_targets_from_targetable project
discussion2.save!
end
get "/discussions?targetable_id=#{project.id}&targetable_type=Project", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body).count).to eq(2)
end
end
describe "when asking for a user" do
let!(:project) { create_on_schema :project, account.subdomain }
it "should return empty discussions" do
get "/discussions?user_id=#{user.id}", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body).count).to eq(0)
end
it "should return one discussions" do
on_schema account.subdomain do
discussion = build(:discussion, user_id: user.id)
discussion.build_targets_from_targetable project
discussion.save!
end
get "/discussions?user_id=#{user.id}", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body).count).to eq(1)
end
it "should return two discussions" do
on_schema account.subdomain do
task = build(:task_with_users_and_project, taskable_id: project.id, taskable_type: 'Project')
task.save!
discussion = build(:discussion, user_id: user.id)
discussion.build_targets_from_targetable task
discussion.save!
discussion2 = build(:discussion, content: 'TESSSSTTTTTIIIINNNG', user_id: user.id, title: 'Test2')
discussion2.build_targets_from_targetable project
discussion2.save!
end
get "/discussions?user_id=#{user.id}", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body).count).to eq(2)
end
end
end
describe "POST /discussions" do
let!(:project) { create_on_schema :project, account.subdomain }
it "should return 201 with flash and create one target" do
discussion = attributes_for(:discussion, user_id: user.id)
post "/discussions", {discussion: discussion, targetable_id: project.id, targetable_type: 'Project'}, format: :json
expect(last_response.status).to eq(201)
expect(JSON::parse(last_response.body)["flash"]).to eq("Discussão criada com sucesso.")
expect(JSON::parse(last_response.body)["status"]).to eq("success")
end
it "should return 201 with flash and create two target" do
discussion = attributes_for(:discussion, user_id: user.id)
post "/discussions", {discussion: discussion, targetable_id: project.id, targetable_type: 'Project'}, format: :json
expect(last_response.status).to eq(201)
expect(JSON::parse(last_response.body)["flash"]).to eq("Discussão criada com sucesso.")
expect(JSON::parse(last_response.body)["status"]).to eq("success")
end
it "should not create discussion with invalid arguments" do
discussion = attributes_for(:discussion, content: nil)
post "/discussions", {discussion: discussion, targetable_id: project.id, targetable_type: 'Project'}, format: :json
expect(last_response.status).to eq(422)
expect(JSON::parse(last_response.body)["errors"]).to have_key("content")
end
it "should return 404 if the targetable_type isn't a Targetable" do
discussion = attributes_for(:discussion)
post "/discussions", {discussion: discussion, targetable_id: project.id, targetable_type: 'User'}, format: :json
expect(last_response.status).to eq(404)
end
it "should return 404 if the targetable_type a valid class" do
discussion = attributes_for(:discussion)
post "/discussions", {discussion: discussion, targetable_id: project.id, targetable_type: 'InvalidClass'}, format: :json
expect(last_response.status).to eq(404)
end
end
describe "GET /discussions/:id" do
let!(:discussion) { create_on_schema :discussion, account.subdomain }
it "should return 200 when discussion exists" do
get "/discussions/#{discussion.id}", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body)["content"]).to eq(discussion.content)
end
it "should return 404 when discussion doesn't exist" do
get "/discussions/1337", format: :json
expect(last_response.status).to eq(404)
end
end
describe "PUT /discussions/:id" do
let!(:discussion) { create_on_schema :discussion, account.subdomain }
it "should edit the discussion" do
put "/discussions/#{discussion.id}", {discussion: {content: 'testing'}}, format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body)["discussion"]["content"]).to eq('testing')
expect(JSON::parse(last_response.body)["flash"]).to eq('Discussão alterada com sucesso.')
expect(JSON::parse(last_response.body)["status"]).to eq('success')
end
it "should not edit the discussion with invalid attributes" do
put "/discussions/#{discussion.id}", {discussion: {content: ''}}, format: :json
expect(last_response.status).to eq(422)
expect(JSON::parse(last_response.body)).to have_key("errors")
end
end
describe "DELETE /discussions/:id" do
let!(:discussion) { create_on_schema :discussion, account.subdomain }
it "should destroy the discussion" do
delete "/discussions/#{discussion.id}", format: :json
expect(last_response.status).to eq(200)
expect(JSON::parse(last_response.body)["flash"]).to eq("Discussão removida com sucesso.")
expect(JSON::parse(last_response.body)["status"]).to eq("success")
end
it "should render 404 for a invalid discussion" do
delete "/discussions/1337", format: :json
expect(last_response.status).to eq(404)
end
end
end |
require_relative 'features_helper'
feature 'Add review' do
given!(:book) { FactoryGirl.create(:book) }
given(:user) { FactoryGirl.create(:user) }
scenario 'authenticated user can add review' do
sign_in(user)
visit(book_path(book))
click_on('Leave a Review')
#fill_in('review[rating]', with: '5')
find('#review_rating').find(:xpath, 'option[5]').select_option
fill_in('Text review', with: 'Great book.')
click_on('Add')
expect(page).to have_content('Review was successfully created.')
end
scenario 'user try add not valid review' do
sign_in(user)
visit(book_path(book))
click_on('Leave a Review')
#fill_in('review[rating]', with: '5')
find('#review_rating').find(:xpath, 'option[5]').select_option
click_on('Add')
expect(page).to have_content("Text review can't be blank")
end
scenario 'no login user tries to add review' do
visit(book_path(book))
click_on('Leave a Review')
expect(page).to have_content('You need to sign in or sign up before continuing.')
end
end |
# frozen_string_literal: true
class Company < ApplicationRecord
validates :name, :country, presence: true
belongs_to :student
has_many :cash_managements
validates :name, :uniqueness => true
#class method to find list of companies
def self.list(user)
if user.is_a? Teacher
Company.all #if a user is teacher then return all the company
elsif user.is_a? Student
user.companies #if a user is student then return all his/her company only
end
end
end
|
class CommunitiesController < ApplicationController
before_filter :authenticate_user!, :except => [:index, :show]
has_widgets do |root|
root << widget(:new_community)
root << widget(:community_list)
root << widget(:section_list, :community => @community)
end
def index
if params[:category] && !(params[:category] == "all")
@communities = Community.category(params[:category])
else
@communities = Community.all
end
end
def new
@community = Community.new
end
def create
community = Community.new(params[:community])
community.owner = current_user
community.users << current_user
if community.save
flash[:notice] = "Community has been created."
redirect_to communities_path
end
end
def show
@community = Community.find(params[:id])
@section = @community.sections.first
if @section.nil?
if current_user == @community.the_owner
redirect_to admin_community_url
end
else
redirect_to community_section_url(@community, @section)
# redirect_to section_url(@section)
end
end
def admin
@community = Community.find(params[:id])
end
def update
@community = Community.find(params[:id])
if @community.update_attributes(params[:community])
flash[:notice] = "Community saved successfully."
else
flash[:notice] = "Community save failed."
end
render "admin"
end
def join
@community = Community.find(params[:id])
@community.users << current_user
# @community.save
# current_user.publish_activity(:join, :object => @community, :target_object => @community)
redirect_to community_path(@community)
end
def leave
@community = Community.find(params[:id])
@community.users.delete(current_user)
# current_user.publish_activity(:leave, :object => @community, :target_object => @community)
# @community.save
redirect_to community_path(@community)
end
end
|
require 'rails/generators'
require 'rails/generators/base'
require 'rails/generators/active_record'
class InstallGenerator < Rails::Generators::NamedBase
include ActiveRecord::Generators::Migration
source_root File.expand_path("../templates", __FILE__)
def create_migrations
get_dir_path('migrations').sort.each do |filepath|
name = File.basename(filepath)
migration_template "migrations/#{name}", "db/migrate/#{name}", skip: true
end
end
def create_models
get_dir_path('models').sort.each do |filepath|
name = File.basename(filepath)
copy_file "models/#{name}", "app/models/#{name}"
end
end
def create_views
directory "views/stories", "app/views/stories"
end
def create_routes
route "resources :stories, controller: 'artifacts'"
end
private
def get_dir_path(folder)
Dir["#{self.class.source_root}/#{folder}/*.rb"]
end
end
|
class JpSynthetic < ActiveRecord::Base
# mysql table used
self.table_name = "jp_synthetics"
######################################################
##### table refenrence
######################################################
belongs_to :lexeme, :class_name=>"JpLexeme", :foreign_key=>"sth_ref_id"
has_many :other_properties, :class_name=>"JpSyntheticNewPropertyItem", :foreign_key=>"ref_id", :dependent=>:destroy
def self.load_struct_from_json(options, current_level = 0, current_max_level = 0)
temp_sth_struct_ary = []
properties_ary = []
sub_json_struct = {}
current_sth_surface = ''
options[:json_struct].each do |item|
case item
when Array
current_max_level = current_max_level + 1
temp_sth_struct_ary << "meta_#{current_max_level}"
sub_json_struct[current_max_level] = item
when Hash
if (item.keys.size == 1) && (item.keys[0] =~ /^\d+$/)
temp_sth_struct_ary << item.keys[0]
else
properties_ary = item.inject([]) do |temp_ary, inner|
unless inner[1].blank?
case inner[0]
when 'sth_surface' then current_sth_surface = inner[1]
else
property = JpNewProperty.find_by_section_and_property_string('synthetic', inner[0])
temp_value = case property.type_field
when 'category' then JpProperty.find_item_by_tree_string_or_array(inner[0], inner[1]).property_cat_id
when 'text' then inner[1]
when 'time' then inner[1].to_formatted_s(:db)
end
temp_ary << {:property_id => property.id, :type => property.type_field, :value => temp_value}
end
end
temp_ary
end
end
end
end
new_meta_struct = create!(
:sth_ref_id => options[:lexeme].id,
:sth_meta_id => current_level,
:sth_struct => temp_sth_struct_ary.map{|x| "-#{x}-"}.join(','),
:sth_surface => current_sth_surface,
:sth_tagging_state => options[:tagging_state],
:log => options[:log],
:modified_by => options[:modified_by]
)
properties_ary.each do |item|
JpSyntheticNewPropertyItem.create!(
:property_id => item[:property_id],
:ref_id => new_meta_struct.id,
item[:type].intern => item[:value]
)
end
sub_json_struct.each do |key, value|
current_max_level = load_struct_from_json(options.update(:json_struct => value), key, current_max_level)
end
return current_max_level
end
def self.destroy_struct(lexeme_id)
transaction do
find(:all, :conditions=>["sth_ref_id=?", lexeme_id]).each{|sub_structure| sub_structure.destroy}
end
end
def sth_tagging_state_item
JpProperty.find(:first, :conditions=>["property_string='sth_tagging_state' and property_cat_id=?", self.sth_tagging_state])
end
belongs_to :annotator, :class_name => "User", :foreign_key => "modified_by"
def method_missing(selector, *args)
string = selector.to_s
if (string =~ /=$/) != nil
method = string.chop
equals = 1
else
method = string
equals = 0
end
if JpNewProperty.exists?(:property_string=>method, :section=>"synthetic")
property = JpNewProperty.find(:first, :conditions=>["property_string=? and section='synthetic'", method])
type_field = property.type_field
item = JpSyntheticNewPropertyItem.find(:first, :conditions=>["property_id=? and ref_id=?", property.id, self.id])
if equals == 1
unless type_field != "category" or JpProperty.exists?(:property_string=>method, :property_cat_id=>args[0])
raise "undefined method"
end
if item.blank?
return JpSyntheticNewPropertyItem.create!(:property_id=>property.id, :ref_id=>self.id, type_field=>args[0]) rescue raise "undefined method"
else
return item.update_attributes!(type_field=>args[0]) rescue raise "undefined method"
end
elsif equals == 0
if item.blank?
return nil
else
return item[type_field]
end
end
else
super
end
end
######################################################
##### validation
######################################################
validates_uniqueness_of :sth_ref_id, :scope => [:sth_meta_id]
######################################################
##### method
######################################################
def get_display_string
string_array = []
sth_struct.split(',').map{|item| item.delete('-')}.each{|part|
if part =~ /^\d+$/
string_array << JpLexeme.find(part.to_i).surface
elsif part =~ /^meta_(.*)$/
string_array << JpSynthetic.find(:first, :conditions=>["sth_ref_id=? and sth_meta_id=?", sth_ref_id, $1.to_i]).sth_surface
end
}
return string_array.join(', ')
end
def get_dump_string(property_list)
dump_string_array = []
property_list << ['sth_surface', nil, nil]
property_hash = property_list.inject({}) do |temp_hash, property|
case property[0]
when 'sth_surface' then temp_hash['sth_surface'] = sth_surface
else
valid_pro = send(property[0])
temp_hash[property[0]] = if valid_pro.blank? then ''
else
case property[2]
when 'category' then JpProperty.find(:first, :conditions=>["property_string=? and property_cat_id=?", property[0], valid_pro]).tree_string.toutf8
when 'text' then valid_pro
when 'time' then valid_pro.to_formatted_s(:number)
end
end
end
temp_hash
end
dump_string_array << property_hash unless property_hash.blank?
sth_struct.split(',').map{|item| item.delete('-')}.each{|part|
if part =~ /^\d+$/
dump_string_array << {part => JpLexeme.find(part.to_i).surface}
elsif part =~ /^meta_(.*)$/
dump_string_array << JpSynthetic.find(:first, :conditions=>["sth_ref_id=? and sth_meta_id=?", sth_ref_id, $1.to_i]).get_dump_string(property_list)
end
}
return dump_string_array
end
end |
## Classes
# as a programmer, you'll often want to model some object and the properties
#of the object, For example, a social media site may need to mdoel a user with their
#user name and a profiel picture. Or perhaps a music site may need to model a song
#with it's title, genre, and duration. Following App Academy tradition,
#let's say we wanted to model some Cats in ruby! our cats! will have name, colors, and age
# ex of repeated functions
cat_1 = {name: "Sennacy", color: "brown", age: 3}
cat_2 = {name: "Whiskers", color: "white", age: 5}
cat_3 = {name: "Garfield", color: "orange", age: 7}
# how it can be fixed
class Cat
def initialize(name, color, age)
@name = name
@color = color
@age = age
end
end
#three important things about the code above
# * to create a class we use the class keyword
# * the name of a class must begin with a capital letter
#we can define methods within a class
# the #initialize method is a special method name that we will use when creating cats.
# the method expects 3 parameter, name, color, and age
# @ in front of those 3 params make it an instance variable
### initializing new cats
cat_1 = Cat.new("Sennacy", "brown", 3)
cat_2 = Cat.new("Whiskers", "white", 5)
# to create a new cat, #new method must be called on a Cat class,
#this means # new method calls upon # initialize method
## get_name method
class Cat
def initialize(name, color, age)
@name = name
@color = color
@age = age
end
def get_name
@name
end
end
cat_1 = Cat.new("Sennacy", "brown", 3)
p cat_1.get_name # "Sennacy"
# get_.name has to be called on the instance of the variable not the class it self
# the method is used to get the local variable set for the class
# it can be smplified as followed for more options
class Cat
def initialize(name, color, age)
@name = name
@color = color
@age = age
end
def name
@name
end
def age
@age
end
end
cat_1 = Cat.new("Sennacy", "brown", 3)
p cat_1.name # "Sennacy"
p cat_1.age # 3
cat_2 = Cat.new("Whiskers", "white", 5)
p cat_2.name # "Whiskers"
p cat_2.age # 5
p cat_2.color # This will give NoMethodError: undefined method `color'
# getter methods cannot be used to change the value of a certain variable
class Cat
def initialize(name, color, age)
@name = name
@color = color
@age = age
end
def name
@name
end
end
cat_1 = Cat.new("Sennacy", "brown", 3)
p cat_1.name # "Sennacy"
cat_1.name = "Kitty" # This will give NoMethodError: undefined method `name='
# writing the setter method # note that only the block of code inside is method
#is more important than the one outside
class Cat
def initialize(name, color, age)
@name = name
@color = color
@age = age
end
# getter
def age
@age
end
# setter
def age=(number)
@age = number
end
end
cat_1 = Cat.new("Sennacy", "brown", 3)
p cat_1 #<Cat:0x007f8511a6f340 @age=3, @color="brown", @name="Sennacy">
cat_1.age = 42
p cat_1 #<Cat:0x007f8511a6f340 @age=42, @color="brown", @name="Sennacy">
# space between parantheis and equal sign can be omitted as well as the paranthesis
###--------- beyond getter and setter
class Cat
def initialize(name, color, age)
@name = name
@color = color
@age = age
end
def purr
if @age > 5
puts @name.upcase + " goes purrrrrr..."
else
puts "..."
end
end
end
cat_1 = Cat.new("Sennacy", "brown", 10)
cat_1.purr # "SENNACY goes purrrrrr..."
cat_2 = Cat.new("Whiskers", "white", 3)
cat_2.purr # "..."
### ----------- instance versus class variables
# as seen in the previous, instance varialbes or attributes are denoted with @
# and they are typically assigned to the initialize method
# class variables are denoted with two @
# ex
class Car
@@num_wheels = 4 ## class variable accessible and attributed equally for
# any creation of Car
def initialize(color)
@color = color
end
# getter for @color instance variable
def color
@color
end
# getter for @@num_wheels class variable
def num_wheels
@@num_wheels
end
end
car_1 = Car.new("red")
p car_1.num_wheels # 4
car_2 = Car.new("black")
p car_2.num_wheels # 4
# this means that when initializoing a car object,
# only the color will need to be defined, and the number of wheel will be
#already set to the shared class varialbe
# this means that if the class varialb is changed to a different value
#all instances where the class variables are shared will also change
# ex.
class Car
@@num_wheels = 4
def self.upgrade_to_flying_cars
@@num_wheels = 0
end
def initialize(color)
@color = color
end
def num_wheels
@@num_wheels
end
end
car_1 = Car.new("red")
car_2 = Car.new("black")
p car_1.num_wheels # 4
p car_2.num_wheels # 4
Car.upgrade_to_flying_cars
p car_1.num_wheels # 0
p car_2.num_wheels # 0
car_3 = Car.new("silver")
p car_3.num_wheels # 0
### ----- class constants
# class constants are created when you want a certain variable not to be altered
# ex
class Car
NUM_WHEELS = 4
def self.upgrade_to_flying_cars
NUM_WHEELS = 0 # SyntaxError: dynamic constant assignment
end
def initialize(color)
@color = color
end
def num_wheels
NUM_WHEELS
end
end
car_1 = Car.new("red")
car_2 = Car.new("black")
p car_1.num_wheels # 4
p car_2.num_wheels # 4
Car.upgrade_to_flying_cars
summary
# instance variable will be varaiable distinct in each instances of the class
## class varialbes will be shared amongst all instances of the class,
# changing this variable will result in change of all instances sharing this variable
##CLASS_CONSTANT will be shared amongst all class but cannot be changed.
##### -------------- Instance methods and class methods
## **** Instance methods are methods that are called on instances of class
class Dog
def initialize(name, bark)
@name = name
@bark = bark
end
def speak # this is an instance method that is called on an instance of a class
@name + " says " + @bark
end
end
my_dog = Dog.new("Fido", "woof")
my_dog.speak # "Fido says woof"
other_dog = Dog.new("Doge", "much bork")
other_dog.speak # "Doge says much bork"
# speak will be called on an instance made using Dog.new method
#Remember that if something is an instance of Dog, it is an object with a @name
#and @bark. Since my_dog and other_dog are instances, when we call speak on them
#respectively, we can get different behavior because they can have different @name
#and @bark values. An instance method depends on the attributes or instance
#variables of an instance.
##### --- Class methods
# class methods are usually called on #self when creating
# this refers to the Class it belongs to
# ex.
class Dog
def initialize(name, bark)
@name = name
@bark = bark
end
def self.growl # class method
"Grrrrr"
end
end
Dog.growl # Grrrrr
#Since growl is a class method, we cannot call it on an instance; instead
#we call it on the Dog class directly . A class method cannot refer to any instance
# attributes like @name and @bark! As programmers, we'll choose to build class
#methods for added utility.
# another use of class method
class Dog
def initialize(name, bark)
@name = name
@bark = bark
end
def self.whos_louder(dog_1, dog_2) # this compares the two instance variable of the instances of dogs
if dog_1.bark.length > dog_2.bark.length
return dog_1.name
elsif dog_1.bark.length < dog_2.bark.length
return dog_2.name
else
return nil
end
end
def name
@name
end
def bark
@bark
end
end
## summar
#Class#method_name means method_name is an instance method
#Class::method_name means method_name is a class method
|
# frozen_string_literal: true
require 'securerandom'
class Part < ApplicationRecord
has_many :sub_parts, inverse_of: :part
accepts_nested_attributes_for :sub_parts, allow_destroy: true
validates :identifier, presence: true, uniqueness: true
update_index 'parts', :self
after_initialize do
self.identifier = identifier.presence || generate_unique_identifier if new_record?
end
def self.permitted_params
%w(identifier description)
end
private
INVALID_CHARACTERS = /[o0l1]/
def generate_unique_identifier
SecureRandom.hex.remove(INVALID_CHARACTERS)[0...5].upcase
end
end
|
class AddAreaToVillages < ActiveRecord::Migration
def change
add_column :villages, :area, :integer
end
end
|
class Logo < ActiveRecord::Base
has_attached_file :image,
:styles => { :original => "800x800", :large => "100x200", :medium => "50x100", :small => "25x50" },
:default_style => :large
belongs_to :company
# We shouldn't have a logo without an attached image
validates_attachment_presence :image
validates_attachment_content_type :image, :content_type => [
'image/jpeg',
'image/pjpeg', # for progressive Jpeg ( IE mine-type for regular Jpeg )
'image/png',
'image/x-png', # IE mine-type for PNG
'image/gif'
]
validates_attachment_size :image, :less_than => 1024 * 1024, :message => "The uploaded image is too large. Please make the image less than 1MB"
end
|
class AddRangeMaxToPayment < ActiveRecord::Migration[6.0]
def change
add_column :payments, :range_max, :decimal
end
end
|
### Testing task 2 code:
# Carry out dynamic testing on the code below.
# Correct the errors below that you spotted in task 1.
require_relative('card.rb') # 5. changed folder
class CardGame #6 changed test name to TestCardGame
def self.check_for_ace(card) # 4. fixed lower case snake case, 7. changed to self
return true if card.value == 1 #9 changed to ==
false #15 refactored to remove else and use implicit return
end
def self.highest_card(card1, card2) # 2. fixed dif to def, 3. fixed comma between parameters 8. changed to self
return card.name if card1.value > card2.value
card2 #16 refactored to remove else and use implicit return
end
def self.cards_total(cards)
total = 0 #10.changed to =0
for card in cards
total += card.value
end
"You have a total of " + total.to_s #11.added .to_s #12moved return outside end #13 added space
end # 17 use implicit return
end # 1. fixed position of end
#14spacing and indenting
|
require 'cuba/test'
require './fizz_buzz_app.rb'
scope do
test 'root' do
get '/'
assert last_response.body.include?('Welcome to Mario\'s FizzBuzz')
end
test 'any page should redirect to root' do
get '/any-page'
follow_redirect!
assert last_response.body.include?('Welcome to Mario\'s FizzBuzz')
end
end |
RSpec.describe User, "login" do
feature "Log in" do
let!(:user) {FactoryGirl.create :user}
scenario "Successful sign in" do
visit "/users/sign_in"
fill_in "E-mail", with: user.email
fill_in "Mật khẩu", with: user.password
click_button "Đăng nhập"
expect(page).to have_content "Đăng nhập thành công"
end
scenario "Sign in failed" do
visit "/users/sign_in"
fill_in "E-mail", with: user.email
fill_in "Mật khẩu", with: "12345678"
click_button "Đăng nhập"
expect(page).to have_content "Đăng ký Email hoặc mật khẩu không chính xác"
end
end
end
|
class Greeter
@@salutation = 'hello'
def initialize(name)
@name = name
end
def greet
puts "#{@@salutation}, #{@name}"
end
def self.perform
new('world').greet
end
end
Greeter.perform
module Counter
def initialize
@count = 0
end
def increment
@count = count + 1
end
def count
@count || 0
end
end
class A
extend Counter
end
puts A.count
A.increment
puts A.count |
class Group < ApplicationRecord
has_many :users, optional: true
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_and_belongs_to_many :homeworks
has_many :registries, through: :homeworks
def completed_tasks(user)
user.registries.where(carried_out: true, user_id: user.id)
end
end
|
class Publication < ActiveRecord::Base
include PublicActivity::Model
mount_uploader :image, AvatarUploader
belongs_to :project
belongs_to :user
has_many :comments, dependent: :destroy
has_many :shares, dependent: :destroy
has_many :activities, as: :trackable, class_name: 'PublicActivity::Activity', dependent: :destroy
end
|
class User < ApplicationRecord
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
# setup relations, ensure to prevent orphan records with dependent: :destroy
has_many :reviews, dependent: :destroy
has_many :reviews_made, class_name: 'Review', foreign_key: :reviewer_id, dependent: :destroy
has_one_attached :profile_pic
has_many :messages, dependent: :destroy
has_and_belongs_to_many :printers
has_and_belongs_to_many :filaments
has_and_belongs_to_many :chatrooms, dependent: :destroy
# run the make owner method before saving user record
before_save :make_owner
# use rails scope to give ability to filter in a complex way based on distance from a location
scope :within_range, lambda { |lat, long, dist|
dist *= 0.009009009 # multiplier to convert kilometers to degrees in latitude and longitude
where.not(address: nil)
.where(latitude: (lat - dist)..(lat + dist))
.where(longitude: (long - dist)..(long + dist))
}
# method to find the user's name to be displayed publicly to other users
def public_name
nickname || first_name
end
# method to provide the role of owner when a user adds their address to their account
def make_owner
add_role :owner if !(has_role? :owner) && !address_change_to_be_saved.nil?
end
# method to calculate a user's average rating from the ratings attached to their reviews
def average_rating
ratings = reviews.pluck(:rating)
return 0 if ratings.empty?
ratings.sum / ratings.length.to_f
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
u = User.first
raise 'You need to create first user.' if u.nil?
hash = {
data: {
name: "Obama",
gender: "male",
age: 55,
hobit: %w(guitar cat code coffee bear),
balance: 11000000,
status: "mad",
address: {
country: "Taiwan",
city: "Taipei",
region: "XinYi",
Street: "DaAnRoad"
}
}
}
u.save_setting(hash) |
class RemoveValueFromPolls < ActiveRecord::Migration[5.2]
def change
remove_column :polls, :value
add_column :polls, :value, :float
end
end
|
class HumanPlayer
attr_accessor :mark_value
def initialize(mark_value)
@mark_value = mark_value
end
def get_position
puts "Player #{mark_value.to_s}, enter two numbers representing a position in the format `row col`"
pos = gets.chomp.split(' ').map(&:to_i)
raise 'invalid, retry!' if pos.length != 2
pos
end
end |
require 'test_helper'
class ResultTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test 'should not save new empty user' do
posled = Result.new
assert posled.save
end
=begin
test 'should not save duplicate data' do
@param = '1 2 3 3 4 5 6 7 8 1 2 3 3 3 3 34 35 72 96 15 35 46 73'
@result = [[3,4,5,6,7,8], [3,34,35,72,96], [15,35,46,73], [1,2,3], [1,2,3]]
new_result = Result.create(param: @param.to_s, res: @result.to_s)
if Result.find_by(param: "#{@param}") == nil
assert false
else
tmp_res = Result.find_by(param: @param)
assert true
end
end
=end
test 'value should be unique' do
test_rec = Result.new param: '1 2 3', res: '1 2 3'
assert test_rec.save
test_rec = Result.new param: '1 2 3', res: '1 2 3'
assert_not test_rec.save
end
test 'value should be' do
test_rec = Result.new param: '1 2 3', res: '1 2 3'
assert test_rec.save
test_rec = Result.new param: nil, res: nil
assert_not test_rec.save
end
end
|
module Fog
module Compute
class Google
class Mock
def add_target_pool_health_checks(_target_pool, _region, _health_checks)
# :no-coverage:
Fog::Mock.not_implemented
# :no-coverage:
end
end
class Real
def add_target_pool_health_checks(target_pool, region, health_checks)
check_list = health_checks.map do |health_check|
::Google::Apis::ComputeV1::HealthCheckReference.new(
health_check: health_check
)
end
@compute.add_target_pool_health_check(
@project,
region.split("/")[-1],
target_pool,
::Google::Apis::ComputeV1::AddTargetPoolsHealthCheckRequest.new(
health_checks: check_list
)
)
end
end
end
end
end
|
class Holiday
attr_reader :next_three_holidays
def initialize
holiday_service = HolidayService.new
@next_three_holidays = holiday_service.get_holiday_data[0..2]
end
end
|
# encoding: utf-8
class Moip::Plan < Moip::Model
include HTTParty
include Moip::Header
# see http://moiplabs.github.io/assinaturas-docs/api.html#criar_plano
attr_accessor :code, :name, :description, :amount,
:setup_fee, :interval, :billing_cycles,
:status, :max_qty, :plans
validates :code, :name, :amount, :presence => true
def attributes
{
"code" => code,
"name" => name,
"description" => description,
"amount" => amount,
"setup_fee" => setup_fee,
"interval" => interval,
"billing_cycles" => billing_cycles,
"status" => status,
"max_qty" => max_qty
}
end
def interval= options = {}
@interval = {}
@interval.merge! :length => options[:length]
@interval.merge! :unit => options[:unit]
end
def interval
return nil if @interval.nil?
@interval.delete_if {|key, value| value.nil? }
if @interval.size > 0
@interval
else
nil
end
end
def plans= hash
@plans = []
hash.each do |e|
plan = self.class.new
plan.set_parameters e
@plans << plan
end
@plans
end
# see http://moiplabs.github.io/assinaturas-docs/api.html#listar_plano
def load
list = self.class.get(base_url(:plans), default_header).parsed_response
self.plans = list["plans"]
end
# metodo que envia as informações para a API do moip e cria um novo plano
# see http://moiplabs.github.io/assinaturas-docs/api.html#criar_plano
def create
if self.valid?
response = self.class.post(base_url(:plans), default_header(self.to_json)).parsed_response
self.validate_response response
else
false
end
end
# see http://moiplabs.github.io/assinaturas-docs/api.html#consultar_plano
def find code
response = self.class.get(base_url(:plans, :code => code), default_header).parsed_response
self.set_parameters response unless response.nil?
end
# see http://moiplabs.github.io/assinaturas-docs/api.html#alterar_plano
def update
if self.valid?
self.class.put(base_url(:plans, :code => self.code), default_header(self)).parsed_response
true
else
false
end
end
# see http://moiplabs.github.io/assinaturas-docs/api.html#ativar_desativar_plano
def activate
if self.status != "activate"
self.status = "activate"
self.class.put(base_url(:plans, :code => self.code, :status => "activate"), default_header).parsed_response
true
end
end
# see http://moiplabs.github.io/assinaturas-docs/api.html#ativar_desativar_plano
def inactivate
if self.status != "inactivate"
self.status = "inactivate"
self.class.put(base_url(:plans, :code => self.code, :status => "inactivate"), default_header).parsed_response
true
end
end
end
|
Rails.application.routes.draw do
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'home#index'
get 'about', to: 'home#about'
get 'methodology', to: 'home#methodology'
resources :products, only: [:index, :show, :create] do
resources :subscriptions, only: :create
end
resources :models
resources :console, only: [:index, :new, :create]
end
|
class ActivityPost < ApplicationRecord
extend FriendlyId
max_paginates_per 5
friendly_id :title, use: :slugged
mount_uploader :image, ImageUploader
belongs_to :user
after_initialize :set_defaults
validate :check_time
# validate :check_start_date_and_end_date
validates_presence_of :title, :description, :venue
# validates_presence_of :start_date, :end_date, :start_time, :end_time
# TODO - MOVE CHECK_TIME METHOD TO PRIVATE
private
def set_defaults
self.start_date ||= Date.today
self.end_date ||= Date.today + 3.days
end
def check_start_date_and_end_date
if (start_date && end_date != nil ) && (start_date > end_date)
errors.add(:start_date, "can not be earlier than end date")
end
end
end
|
require 'json'
module Actions
module GladiatorsActions
def generate_actions(data)
data.each do |k, v|
if v.is_a?(Hash)
v.each do |k, v|
if k == "name"
define_method ("greeting") do
p "Going to death #{v}, salute you!"
end
elsif k == "weapon"
v.each do |v|
define_method ("attack_vis_#{v}") do
p "Being in a fighting stance, gladiator rushed to the attack swinging #{v}"
end
end
end
end
end
end
end
end
def self.included(base)
base.extend(GladiatorsActions)
end
end
RESPONSE = '{"gladiator":{"personal_data":{"name": "Staros", "gender":"male", "age":27},
"skills":["swordsman","spearman","bowmen"],
"amunition":{"weapon":["trident","net","dagger"],
"armor":[{"head":"no","torso":"belt","limbs":"braser"}]
}}}'
response = JSON.parse(RESPONSE)
Gladiator = Struct.new(*response["gladiator"].keys.collect(&:to_sym)) do
def how_old?
p "His age is #{personal_data["age"]}"
end
def spearman?
p "Our gladiadiator #{skills.select{|x| x== "spearman" }[0]}! He will make a good retiarius"
end
def have_weapon?
weapon = "no"
amunition.each{|x| Hash[*x].each_pair{|key, value| if key == "weapon" then weapon=value end}}
p "Glagiator #{personal_data["name"]} is carrying a #{weapon.join(", ")}"
end
end
Gladiator.class_eval do
include Actions
generate_actions (response["gladiator"]){p "Being in a fighting stance, gladiator rushed to the attack swinging #{v}"}
end
person = Gladiator.new(*response["gladiator"].values)
p person.public_methods(false)
person.how_old?
person.spearman?
person.have_weapon?
person.greeting
person.attack_vis_trident
person.attack_vis_net
person.attack_vis_dagger
|
Sequel.migration do
change do
create_table :schools do
foreign_key :id, :places
String :name
String :school_type
Integer :gs_rating
Integer :parent_rating
String :grade_range
Integer :enrollment
String :website
end
end
end
|
class Tag < ActiveRecord::Base
# Remember to create a migration!
has_many :taggings
has_many :questions, through: :taggings
validates_uniqueness_of :description
validates :description, presence: true
end
|
require 'rails_helper'
RSpec.describe 'admin price update', settings: false do
before :example do
sign_in_to_admin_area
end
it 'updates zone' do
price = create(:price)
create(:zone, id: 2)
patch admin_price_path(price), price: attributes_for(:price, zone_id: '2')
price.reload
expect(price.zone_id).to eq(2)
end
it 'updates operation category' do
price = create(:price, operation_category: Billing::Price.operation_categories.first)
patch admin_price_path(price),
price: attributes_for(:price, operation_category: Billing::Price.operation_categories.second)
price.reload
expect(price.operation_category).to eq(Billing::Price.operation_categories.second)
end
it 'updates duration in months' do
price = create(:price, duration: '3 mons')
patch admin_price_path(price), price: attributes_for(:price, duration: '6 mons')
price.reload
expect(price.duration).to eq('6 mons')
end
it 'updates duration in years' do
price = create(:price, duration: '1 year')
patch admin_price_path(price), price: attributes_for(:price, duration: '2 years')
price.reload
expect(price.duration).to eq('2 years')
end
it 'updates valid_from' do
price = create(:price, valid_from: '2010-07-05')
patch admin_price_path(price), price: attributes_for(:price, valid_from: '2010-07-06')
price.reload
expect(price.valid_from).to eq(Time.zone.parse('06.07.2010'))
end
it 'updates valid_to' do
price = create(:price, valid_to: '2010-07-05')
patch admin_price_path(price), price: attributes_for(:price, valid_to: '2010-07-06')
price.reload
expect(price.valid_to).to eq(Time.zone.parse('06.07.2010'))
end
it 'redirects to :index' do
price = create(:price)
patch admin_price_path(price), price: attributes_for(:price)
expect(response).to redirect_to admin_prices_url
end
end
|
class CreateBrochures < ActiveRecord::Migration
def change
create_table :brochures do |t|
t.belongs_to :type
t.string :name
t.boolean :rep_enabled
t.boolean :dist_enabled
t.string :kind
t.integer :inventory
t.integer :total
t.datetime :deleted_at, :index => true
t.timestamps null: false
end
end
end
|
class Book
include Mongoid::Document
field :name, type: String
field :store_id, type: String
end
|
# frozen_string_literal: true
Current::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
host = 'http://127.0.0.1'
config.action_mailer.default_url_options = { host: host, port: 3000 }
config.action_mailer.asset_host = host
config.action_mailer.raise_delivery_errors = false
config.action_mailer.show_previews = true
config.action_mailer.delivery_method = :smtp
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.logger = Logger.new(STDOUT)
config.log_level = :INFO
# Loading classes policy. true to load at start. false to load as needed
config.eager_load = false
config.force_ssl = false
config.hosts << 'da24-161-22-56-164.sa.ngrok.io'
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :my_projects, class_name: "Project", foreign_key: :owner_id
has_many :comments, foreign_key: :owner_id
has_and_belongs_to_many :projects
validates_presence_of :name
scope :free_users, -> (project) { User.where.not(id: (project.user_ids + [project.owner.id])) }
# def self.free_users(project)
# ids = project.user_ids << project.owner.id
# User.where.not(id: ids)
# end
end
|
require 'spec_helper'
require 'greenpeace/configuration/requirement'
describe Greenpeace::Configuration::Requirement do
subject do
Greenpeace::Configuration::Requirement.new(
:key,
{ type: :int, doc: 'DOC', defaults: { development: 5 } },
'development')
end
describe '#identifier' do
it 'returns the stringified key' do
expect(subject.identifier).to eq('key')
end
end
describe '#value' do
context 'when the environment does not match the default' do
subject do
Greenpeace::Configuration::Requirement.new(
:key,
{ type: :int, doc: 'DOC', defaults: { development: 5 } },
'production')
end
context 'when an empty value is in the ENV' do
before(:each) { configure_env_value '' }
it 'raises an error' do
expect { subject.value }.to raise_error
end
end
context 'when a nil value is in the ENV' do
before(:each) { configure_env_value nil }
it 'raises an error' do
expect { subject.value }.to raise_error
end
end
context 'when a valid value is in the ENV' do
before(:each) { configure_env_value '10' }
it 'returns the value' do
expect(subject.value).to eq(10)
end
end
end
context 'when the environment matches the default' do
subject do
Greenpeace::Configuration::Requirement.new(
:key,
{ type: :int, doc: 'DOC', defaults: { development: 5 } },
'development')
end
context 'when an empty value is in the ENV' do
before(:each) { configure_env_value '' }
it 'returns the default value' do
expect(subject.value).to eq(5)
end
end
context 'when a nil value is in the ENV' do
before(:each) { configure_env_value nil }
it 'returns the default value' do
expect(subject.value).to eq(5)
end
end
context 'when a valid value is in the ENV' do
before(:each) { configure_env_value '10' }
it 'returns the value' do
expect(subject.value).to eq(10)
end
end
end
end
end
|
class UserItemsController < ApplicationController
before_action :set_user_item, only: [:destroy]
# POST /user_items
def create
@user_item = UserItem.new(user_item_params)
@user = User.find(params[:user_id])
@item = Item.find(params[:item_id])
if @user.bank <= @item.price
render json: {poor: true}, status: :unprocessable_entity
elsif @user_item.save
@user.bank -= @item.price
@user.save
render json: @user_item, status: :created, location: @user_item
else
render json: @user_item.errors, status: :unprocessable_entity
end
end
# DELETE /user_items/1
def destroy
@user_item.destroy
end
private
def set_user_item
@user_item = UserItem.find(params[:id])
end
def user_item_params
params.require(:user_item).permit(:user_id, :item_id)
end
end
|
# Copyright (c) 2016 Cameron Harper
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'ruby-serial'
module DLMSTrouble
class ModeEPort
def initialize(port, **opts)
puts "opening port '#{port}'"
@port = SerialPort.new(port)
@port.baud = 300
@port.data_bits = 7
@port.parity = 1
@port.read_timeout = opts[:timeout]||1500
@port.flush_input
puts "writing Request..."
@port.write(DirectLocal::Request.new.to_line)
sleep(1)
puts "reading line"
line = @port.readline
puts "expecting Idenfification"
id = DirectLocal::Identification.from_line(line)
puts "device '#{id.id}' answered"
puts "switch to mode E"
DirectLocal::Ack.new(
@port.flush_input
end
def read
end
def write
end
end
module DirectLocal
MODE_A
MODE_B
MODE_C
MODE_D
MODE_E
class Request
def self.from_line(msg)
result = /\/\?(?<addr>[A-Za-z0-9 ]{1,32})?\r\n/.match(msg)
if result.nil?
raise
end
self.new(result[:addr])
end
def initialize(addr=nil)
@addr = addr
end
def to_line
"/?#{@addr}\r\n"
end
end
class Identification
attr_reader :flagID, :baud, :id
def self.from_line(msg)
msg.match(/\/()/
end
def initialize(flagID, baud, id)
@flagID = flagID
@baud = baud
@id = id
end
def to_line
"/#{@flagID}#{@baud}" + ( @id ? "\\W"
end
end
class Ack
def self.from_line(msg)
result = /\x06(?<protocol>)(?<baud>)(?<>)\r\n/.match(msg)
if result.nil?
raise
end
self.new(result[:protocol], result[:baud], result[:])
end
def initialize(protocol, baud, control)
@protocol = protocol
@baud = baud
@control = control
end
def to_line
"\x06#{@protocol}#{@baud}#{@control}\r\n"
end
end
end
end
|
module ApplicationHelper
def statuses
Coupon.statuses.keys.map { |w| [w.humanize, w] }
end
end
|
# The program "product_of_int.rb" modified to include validating user inputs:
def sum_of_int(int)
(1..int).sum
end
def product_of_int(int)
(1..int).to_a.inject(:*)
end
def valid_int?(int)
int.integer? && int > 0
end
def valid_answer?(sum_or_product)
sum_or_product == "s" || sum_or_product == "p"
end
puts "Lets find the sum or product of all numbers between 1 & your chosen integer!"
int = ""
loop do
puts "Please enter an integer greater than 0:"
int = gets.chomp.to_i
if valid_int?(int)
break
else
puts("Hmmm...that doesn't look like a valid number.")
end
end
sum_or_product = ""
loop do
puts "Enter 's' to compute the sum, 'p' to compute the product:"
sum_or_product = gets.chomp.downcase
if valid_answer?(sum_or_product)
break
else
puts "Please input only 's' or 'p' for your answer."
end
end
product = product_of_int(int)
sum = sum_of_int(int)
if sum_or_product == "s"
puts "The sum of the integers between 1 and #{int} is #{sum}."
elsif sum_or_product == "p"
puts "The product of the integers between 1 and #{int} is #{product}"
else
puts "Oh no, that is an unknown operation!"
end
|
module Anetwork
class Messages
# setter and getter varibules
attr_accessor :code , :text , :error , :error_code , :headers , :lang , :config
##
# initialize method
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
# @param [String] lang
def initialize(lang = 'en')
@lang = I18n.locale
if @lang != '' || @lang != nil
lang = @lang
end
@config = eval(File.open(__dir__ + "/errors/#{lang}.rb").read)
end
##
# Request succeeded and contains json result
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [Object] data
# @return [Object]
def succeed(data)
self.set_status_code(200)
.set_status_text('success')
.respond_with_result(data)
end
##
# Delete action is succeed
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [String] message
# @return [Object]
def delete_succeeded(message = nil)
if message == nil
message = @config[:success][:delete]
end
self.set_status_code(200)
.set_status_text('success')
.respond_with_message(message)
end
##
# Update action is succeed
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [String] message
# @return [Object]
def update_succeeded(message = nil)
if message == nil
message = @config[:success][:update]
end
self.set_status_code(200)
.set_status_text('success')
.respond_with_message(message)
end
##
# Insert action is succeed
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [String] message
# @return [Object]
def insert_succeeded(message = nil)
if message == nil
message = @config[:success][:insert]
end
self.set_status_code(200)
.set_status_text('success')
.respond_with_message(message)
end
##
# Delete action is faild
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [String] message
# @return [Object]
def delete_faild(message = nil)
if message == nil
message = @config[:fail][:delete]
end
self.set_status_code(447)
.set_status_text('fail')
.set_error_code(5447)
.respond_with_message(message)
end
##
# Update action is succeed
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [String] message
# @return [Object]
def update_faild(message = nil)
if message == nil
message = @config[:fail][:update]
end
self.set_status_code(449)
.set_status_text('fail')
.set_error_code(5449)
.respond_with_message(message)
end
##
# Insert action is faild
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [String] message
# @return [Object]
def insert_faild(message = nil)
if message == nil
message = @config[:fail][:insert]
end
self.set_status_code(448)
.set_status_text('fail')
.set_error_code(5448)
.respond_with_message(message)
end
##
# Database connection is refused
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
def connection_refused
self.set_status_code(445)
.set_status_text('fail')
.set_error_code(5445)
.respond_with_message
end
##
# Page requested is not found
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
def not_found
self.set_status_code(404)
.set_status_text('fail')
.set_error_code(5404)
.respond_with_message
end
##
# Wrong parameters are entered
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
def wrong_parameters
self.set_status_code(406)
.set_status_text('fail')
.set_error_code(5406)
.respond_with_message
end
##
# Method is not allowed
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
def method_not_allowed
self.set_status_code(405)
.set_status_text('fail')
.set_error_code(5405)
.respond_with_message
end
##
# There ara validation errors
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
def validation_errors(message = nil)
self.set_status_code(420)
.set_status_text('fail')
.set_error_code(5420)
.respond_with_message(message)
end
##
# The request field is not found
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
def request_field_notfound
self.set_status_code(446)
.set_status_text('fail')
.set_error_code(1001)
.respond_with_message
end
##
# The request field is duplicated
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @return [Object]
def request_field_duplicated
self.set_status_code(400)
.set_status_text('fail')
.set_error_code(1004)
.respond_with_message
end
##
# The error message
#
# @author Alireza Josheghani <a.josheghani@anetwork.ir>
# @since 1 Dec 2016
# @param [Object] code
# @return [Object]
def error(code)
self.set_status_code(400)
.set_status_text('fail')
.set_error_code(code)
.respond_with_message
end
end
end
|
class LoginController < ApplicationController
def create
@skater = Skater.find_by(name: params[:name])
if @skater && @skater.authenticate(params[:password])
payload = { skater_id: @skater.id ,name:@skater.name, skater:@skater}
token = encode_token(payload)
render json: { skater: @skater, skater_id: @skater.id, token: token, success: "Welcome back #{@skater.name}"}
else
render json: { errors: [ "That didn't match any skaters" ] }, status: :unprocessable_entity
end
end
end
|
Rails.application.routes.draw do
get 'reviews/new'
get 'reviews/create'
get 'restaurants/index'
get 'restaurants/show'
get 'restaurants/new'
get 'restaurants/create'
root to: 'restaurants#index'
resources :restaurants, only: [:index, :new, :show, :create] do
resources :reviews, only: [:new, :create]
end
end
# Controller:Action
# root GET / restaurants:index - restaurants_path
# restaurants GET /restaurants restaurants:index - restaurants_path
# restaurant GET /restaurants/:id restaurants:show - restaurant_path(restaurant) - send the restaurant with it
# new_restaurant GET /restaurants/new restaurants:new - new_restaurant_path
# POST /restaurants - restaurants:create
# new_restaurant_review GET /restaurants/:restaurant_id/reviews/new - reviews:new - new_restaurant_review_path(restaurant)
# restaurant_reviews 'POST/restaurants/:restaurant_id/reviews' - reviews:create
|
# frozen_string_literal: true
# Custom method to check if string is an integer.
class String
def integer?
self =~ /\A[-+]?\d+\z/
end
end
|
require "./lib/snack"
class VendingMachine
attr_reader :inventory
def initialize
@inventory = []
end
def add_snack(snack)
@inventory << snack
end
def snacks_by_name
@inventory.map do |snack|
snack.name
end
end
def how_many_snacks
@inventory.group_by do |snack|
snack.quantity
end
end
def inventory_by_alphabet
@inventory.group_by do |snack|
snack.name[0]
end
end
def total_num_items
@inventory.reduce(0) do |memo, snack|
memo += snack.quantity
end
end
def first_letters
@inventory.reduce("") do |memo, snack|
memo += snack.name[0]
end
end
def change_indexes
num = 0
@inventory.map do |snack|
num += 1
end
end
end
|
require File.join(File.dirname(__FILE__), 'spec_helper')
require 'barby/barcode/bookland'
include Barby
describe Bookland do
before :each do
@isbn = '968-26-1240-3'
@code = Bookland.new(@isbn)
end
it "should not touch the ISBN" do
@code.isbn.should == @isbn
end
it "should have an isbn_only" do
@code.isbn_only.should == '968261240'
end
it "should have the expected data" do
@code.data.should == '978968261240'
end
it "should have the expected numbers" do
@code.numbers.should == [9,7,8,9,6,8,2,6,1,2,4,0]
end
it "should have the expected checksum" do
@code.checksum.should == 4
end
it "should raise an error when data not valid" do
lambda{ Bookland.new('1234') }.should raise_error(ArgumentError)
end
end
describe Bookland, 'ISBN conversion' do
it "should accept ISBN with number system and check digit" do
code = nil
lambda{ code = Bookland.new('978-82-92526-14-9') }.should_not raise_error
code.should be_valid
code.data.should == '978829252614'
end
it "should accept ISBN without number system but with check digit" do
code = nil
lambda{ code = Bookland.new('82-92526-14-9') }.should_not raise_error
code.should be_valid
code.data.should == '978829252614'
end
it "should accept ISBN without number system or check digit" do
code = nil
lambda{ code = Bookland.new('82-92526-14') }.should_not raise_error
code.should be_valid
code.data.should == '978829252614'
end
end
|
PlaygroundApp::Application.routes.draw do
devise_for :users
devise_scope :user do
get 'sign_in', to: 'devise/sessions#new'
delete 'sign_out', to: 'devise/sessions#destroy'
get 'sign_up', to: 'devise/registrations#new'
end
resources :users, except: [:create] do
member do
match 'delete' => 'users#delete', via: :get
end
end
resources :images, only: [:show]
match 'users/new' => 'users#create', via: :post, as: :create_user
match 'users/:id/password' => 'users#password', via: :get, as: :change_password
match 'users/:id/password' => 'users#update_password', via: :put
match 'users/:id/roles' => 'users#roles', via: :get, as: :edit_roles
match 'users/:id/roles' => 'users#update_roles', via: :put
resources :installations do
member do
match 'delete' => 'installations#delete', via: :get
end
resources :playlists do
member do
match 'delete' => 'playlists#delete', via: :get
match 'scenes' => 'playlists#scenes', via: :get
match 'scenes' => 'playlists#update_scenes', via: :post
end
collection { post :sort }
end
end
match '/installations/:installation_id/playlists/:id/select_scenes' => 'playlists#select_scenes', via: :get, as: :select_scenes
# This route lets us request a specific filename associated with a scene,
# e.g. /scenes/3/data/acetophenone.spt with the filename in params[:filename]
match '/scenes/:id/data/:filename' => 'scenes#data',
constraints: { filename: /.*/ }, as: :scene_file_data, via: :get
# This route is for generating a simple script that just loads the main model and spins it
# for 45 seconds
match 'scenes/:id/simple_script' => 'scenes#simple_script', as: :scene_simple_script, via: :get
# Routes for importing scenes from proteopedia
#
match 'scenes/import' => 'scenes#import', as: :import, via: :get
match 'scenes/import' => 'scenes#create_import', as: :import, via: :post
resources :scenes do
member do
match 'delete' => 'scenes#delete', via: :get
match 'files' => 'scenes#files', via: :get
match 'files' => 'scenes#update_files', via: :post
match 'green' => 'scenes#green', via: :get
match 'green' => 'scenes#update_green', via: :post
get :preview
end
end
resources :playlist_items, only: [:destroy]
match '/home', to: 'home#index'
root to: 'static_pages#home'
match '/help', to: 'static_pages#help'
match '/contact', to: 'static_pages#contact'
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
|
#
# Cookbook:: apache_tomcat
# Recipe:: default
#
# Copyright:: 2017, The Authors, All Rights Reserved.
# Install java
package 'java-1.7.0-openjdk-devel'
# Add a group Tomcat
group 'tomcat'
# Install user
user 'tomcat' do
manage_home false
shell '/bin/nologin'
group 'tomcat'
home '/opt/tomcat'
end
# Download Tomcat
# http://www-us.apache.org/dist/tomcat/tomcat-8/v8.5.11/bin/apache-tomcat-8.5.11.tar.gz
remote_file 'apache-tomcat-8.5.11.tar.gz' do
source 'http://www-us.apache.org/dist/tomcat/tomcat-8/v8.5.11/bin/apache-tomcat-8.5.11.tar.gz'
end
directory '/opt/tomcat' do
action :create
group 'tomcat'
end
# TODO:
execute 'extract apache-tomcat-8 tar to /opt/tomcat' do
command 'tar -C /opt/tomcat -xvzf apache-tomcat-8.5.11.tar.gz --strip-components=1 && cd /opt/tomcat'
creates '/opt/tomcat'
end
#TODO
execute 'chgrp -R tomcat /opt/tomcat'
directory '/opt/tomcat/conf' do
mode '0070'
end
#TODO:
execute 'cd /opt/tomcat && chmod g+r conf/*'
#TODO:
execute 'cd /opt/tomcat && chown -R tomcat webapps/ work/ temp/ logs/'
template '/etc/systemd/system/tomcat.service' do
source 'tomcat.service.erb'
end
#TODO
execute 'systemctl daemon-reload'
#TODO
service 'tomcat' do
action [:start, :enable]
end
|
class SeasonPresenter < AllTimePresenter
def initialize(season:)
@season = season
end
private
def player_source
season.players
end
attr_reader :season
end
|
describe Rfm::Resultset do
# These mocks were breaking the #initialize spec, but only when I added the Layout#modelize spec !?!?
# let(:server) {mock(Rfm::Server)}
# let(:layout) {mock(Rfm::Layout)}
let(:server) {Rfm::Server.allocate}
let(:layout) {Rfm::Layout.allocate}
let(:data) {File.read("spec/data/resultset.xml")}
let(:bad_data) {File.read("spec/data/resultset_with_bad_data.xml")}
subject {Rfm::Resultset.new(data, layout, :server_object=>server)}
before(:each) do
allow(server).to receive(:state).and_return({})
end
describe ".load_data" do
it "loads fmresultset.xml containing portal-meta with duplicate definitions merged" do
handler = Rfm::Resultset.load_data "spec/data/resultset_with_duplicate_portals.xml"
result = handler.result
expect(result.portal_meta["projectlineitemssubitems_pli"]["specialprintinginstructions"].result).to eq("text")
expect(result.portal_meta["projectlineitemssubitems_pli"]["proofwidth"].result).to eq("number")
expect(result.portal_meta["projectlineitemssubitems_pli"]["finishheight"].result).to eq("number")
expect(result.portal_meta["projectlineitemssubitems_pli"]["border"].result).to eq("text")
end
end
# TODO: write specs for data loading & portal loading.
# describe "#initialze" do
# it "calls build_records with record-xml, resultset-obj, field-meta, layout" do
# Rfm::Record.should_receive(:build_records) do |rec,rsl,fld,lay| #|record_xml, resultset, field_meta, layout|
# rec.size.should == 2
# rsl.foundset_count.should == 2
# fld.keys.include?('memokeymaster').should be_true
# lay.should == layout
# end
# subject
# end
#
# it "sets instance variables to non-nil" do
# atrs = [:layout, :server, :field_meta, :portal_meta, :date_format, :time_format, :timestamp_format, :total_count, :foundset_count]
# atrs.each {|atr| subject.send(atr).should_not eql(nil)}
# end
#
# it "loads @portal_meta with portal descriptions" do
# Rfm::Resultset.new(RESULTSET_PORTALS_XML, @Layout, :server_object=>@server).portal_meta['buyouts']['PurchaseOrderNumber'].global.should == 'no'
# end
#
# it "loads data into records & fields, storing errors if data mismatch & ignore_bad_data == true" do
# result_set = Rfm::Resultset.new(bad_data, Memo.layout, :server_object=>Memo.server)
# result_set[1].errors.messages[:TestDate][0].message.should == 'invalid date'
# end
#
# end # initialize
#
# describe ".load_data" do
# it "loads resultset data from filespec or string" do
# result_set = Rfm::Resultset.load_data File.new('spec/data/resultset.xml')
# end
# end
end # Rfm::Resultset
|
module Noodall
class CheckBox < Noodall::Field
key :default, Boolean
end
end |
class FlightsController < ApplicationController
def index
if params.has_key?(:departure)
if params[:departure_airport] != params[:arrival_airport]
@flights = Flight.search(params[:departure], Airport.select(:id).where(code: params[:departure_airport]),
Airport.select(:id).where(code: params[:arrival_airport]))
@passengers = params[:passengers]
else
flash.now[:danger] = "Destination and arrival airports can't be the same."
end
end
end
end
|
class ContenuesController < ApplicationController
def index
@contenues = Contenue.all
end
def show
@contenue = Contenue.find(params[:id])
end
def new
@contenue = Contenue.new
end
def create
@contenue = Contenue.new(product_params)
if @contenue.save
redirect_to contenues_path
else
render :new
end
end
def edit
@contenue = Contenue.find(params[:id])
end
private
def product_params
params.require(:contenue).permit(:title, :url, :abstract)
end
end
|
module RSpec
module Mocks
RSpec.describe Matchers::Receive do
include_context "with syntax", :expect
describe "expectations/allowances on any instance recorders" do
include_context "with syntax", [:expect, :should]
it "warns about allow(Klass.any_instance).to receive..." do
expect(RSpec).to receive(:warning).with(/allow.*any_instance.*is probably not what you meant.*allow_any_instance_of.*instead/)
allow(Object.any_instance).to receive(:foo)
end
it "includes the correct call site in the allow warning" do
expect_warning_with_call_site(__FILE__, __LINE__ + 1)
allow(Object.any_instance).to receive(:foo)
end
it "warns about expect(Klass.any_instance).to receive..." do
expect(RSpec).to receive(:warning).with(/expect.*any_instance.*is probably not what you meant.*expect_any_instance_of.*instead/)
any_instance_proxy = Object.any_instance
expect(any_instance_proxy).to receive(:foo)
any_instance_proxy.foo
end
it "includes the correct call site in the expect warning" do
any_instance_proxy = Object.any_instance
expect_warning_with_call_site(__FILE__, __LINE__ + 1)
expect(any_instance_proxy).to receive(:foo)
any_instance_proxy.foo
end
end
# FIXME: this is defined here to prevent
# "warning: method redefined; discarding old kw_args_method"
# because shared examples are evaluated several times.
# When we flatten those shared examples in RSpec 4 because
# of no "should" syntax, it will become possible to put this
# class definition closer to examples that use it.
if RSpec::Support::RubyFeatures.required_kw_args_supported?
binding.eval(<<-RUBY, __FILE__, __LINE__)
class TestObject
def kw_args_method(a:, b:); end
end
RUBY
end
shared_examples "a receive matcher" do |*options|
it 'allows the caller to configure how the subject responds' do
wrapped.to receive(:foo).and_return(5)
expect(receiver.foo).to eq(5)
end
it 'allows the caller to constrain the received arguments' do
wrapped.to receive(:foo).with(:a)
receiver.foo(:a)
expect {
receiver.foo(:b)
}.to raise_error(/received :foo with unexpected arguments/)
end
it 'allows the caller to constrain the received arguments by matcher' do
wrapped.to receive(:foo).with an_instance_of Float
expect {
receiver.foo(1)
}.to raise_error(/expected.*\(an instance of Float\)/)
receiver.foo(1.1)
end
context 'without yielding receiver' do
# when `yield_receiver_to_any_instance_implementation_blocks` is `true`
# the block arguments are different for `expect` and `expect_any_instance_of`
around do |example|
previous_value = RSpec::Mocks.configuration.yield_receiver_to_any_instance_implementation_blocks?
RSpec::Mocks.configuration.yield_receiver_to_any_instance_implementation_blocks = false
example.run
RSpec::Mocks.configuration.yield_receiver_to_any_instance_implementation_blocks = previous_value
end
it 'allows a `do...end` block implementation to be provided' do
wrapped.to receive(:foo) do
4
end
expect(receiver.foo).to eq(4)
end
if RSpec::Support::RubyFeatures.kw_args_supported?
binding.eval(<<-RUBY, __FILE__, __LINE__)
it 'allows a `do...end` block implementation with keyword args to be provided' do
wrapped.to receive(:foo) do |**kwargs|
kwargs[:kw]
end
expect(receiver.foo(kw: :arg)).to eq(:arg)
end
it 'allows a `do...end` block implementation with optional keyword args to be provided' do
wrapped.to receive(:foo) do |kw: :arg|
kw
end
expect(receiver.foo(kw: 1)).to eq(1)
end
it 'allows a `do...end` block implementation with optional keyword args to be provided' do
wrapped.to receive(:foo) do |kw: :arg|
kw
end
expect(receiver.foo).to eq(:arg)
end
RUBY
end
if RSpec::Support::RubyFeatures.required_kw_args_supported?
binding.eval(<<-RUBY, __FILE__, __LINE__)
it 'allows a `do...end` block implementation with required keyword args' do
wrapped.to receive(:foo) do |kw:|
kw
end
expect(receiver.foo(kw: :arg)).to eq(:arg)
end
it "expects to receive keyword args" do
dbl = instance_double(TestObject)
expect(dbl).to receive(:kw_args_method).with(a: 1, b: 2)
dbl.kw_args_method(a: 1, b: 2)
end
if RUBY_VERSION >= '3.0'
it "fails to expect to receive hash with keyword args" do
expect {
dbl = instance_double(TestObject)
expect(dbl).to receive(:kw_args_method).with(a: 1, b: 2)
dbl.kw_args_method({a: 1, b: 2})
}.to fail_with do |failure|
reset_all
expect(failure.message)
.to include('expected: ({:a=>1, :b=>2}) (keyword arguments)')
.and include('got: ({:a=>1, :b=>2}) (options hash)')
end
end
else
it "expects to receive hash with keyword args" do
dbl = instance_double(TestObject)
expect(dbl).to receive(:kw_args_method).with(a: 1, b: 2)
dbl.kw_args_method({a: 1, b: 2})
end
end
it "expects to receive hash with a hash" do
dbl = instance_double(TestObject)
expect(dbl).to receive(:kw_args_method).with({a: 1, b: 2})
dbl.kw_args_method({a: 1, b: 2})
end
it "expects to receive keyword args with a hash" do
dbl = instance_double(TestObject)
expect(dbl).to receive(:kw_args_method).with({a: 1, b: 2})
dbl.kw_args_method(a: 1, b: 2)
end
RUBY
end
end
it 'allows chaining off a `do...end` block implementation to be provided' do
wrapped.to receive(:foo) do
4
end.and_return(6)
expect(receiver.foo).to eq(6)
end
it 'allows a `{ ... }` block implementation to be provided' do
wrapped.to receive(:foo) { 5 }
expect(receiver.foo).to eq(5)
end
it 'gives precedence to a `{ ... }` block when both forms are provided ' \
'since that form actually binds to `receive`' do
wrapped.to receive(:foo) { :curly } do
:do_end
end
expect(receiver.foo).to eq(:curly)
end
it 'does not support other matchers', :unless => options.include?(:allow_other_matchers) do
expect {
wrapped.to eq(3)
}.to raise_error(UnsupportedMatcherError)
end
it 'does support inherited matchers', :unless => options.include?(:allow_other_matchers) do
receive_foo = Class.new(RSpec::Mocks::Matchers::Receive).new(:foo, nil)
wrapped.to receive_foo
receiver.foo
end
it 'does not get confused by messages being passed as strings and symbols' do
wrapped.to receive(:foo).with(1) { :a }
wrapped.to receive("foo").with(2) { :b }
expect(receiver.foo(1)).to eq(:a)
expect(receiver.foo(2)).to eq(:b)
end
it 'allows do...end blocks to be passed to the fluent interface methods without getting a warning' do
expect(RSpec).not_to receive(:warning)
wrapped.to receive(:foo).with(1) do
:a
end
expect(receiver.foo(1)).to eq(:a)
end
it 'makes { } blocks trump do...end blocks when passed to a fluent interface method' do
wrapped.to receive(:foo).with(1) { :curly } do
:do_end
end
expect(receiver.foo(1)).to eq(:curly)
end
end
shared_examples "an expect syntax allowance" do |*options|
it_behaves_like "a receive matcher", *options
it 'does not expect the message to be received' do
wrapped.to receive(:foo)
expect { verify_all }.not_to raise_error
end
end
shared_examples "an expect syntax negative allowance" do
it 'is disabled since this expression is confusing' do
expect {
wrapped.not_to receive(:foo)
}.to raise_error(/not_to receive` is not supported/)
expect {
wrapped.to_not receive(:foo)
}.to raise_error(/to_not receive` is not supported/)
end
end
shared_examples "an expect syntax expectation" do |*options|
it_behaves_like "a receive matcher", *options
it 'sets up a message expectation that passes if the message is received' do
wrapped.to receive(:foo)
receiver.foo
verify_all
end
it 'sets up a message expectation that fails if the message is not received' do
wrapped.to receive(:foo)
expect {
verify_all
}.to fail
end
it "reports the line number of expectation of unreceived message", :pending => options.include?(:does_not_report_line_num) do
expected_error_line = __LINE__; wrapped.to receive(:foo)
expect {
verify_all
}.to raise_error { |e|
expect(e.backtrace.first).to match(/#{File.basename(__FILE__)}:#{expected_error_line}/)
}
end
it "provides a useful matcher description" do
matcher = receive(:foo).with(:bar).once
wrapped.to matcher
receiver.foo(:bar)
expect(matcher.description).to start_with("receive foo")
end
end
shared_examples "an expect syntax negative expectation" do
it 'sets up a negative message expectation that passes if the message is not received' do
wrapped.not_to receive(:foo)
verify_all
end
it 'sets up a negative message expectation that fails if the message is received' do
wrapped.not_to receive(:foo)
expect_fast_failure_from(receiver, /expected: 0 times.*received: 1 time/m) do
receiver.foo
end
end
it 'supports `to_not` as an alias for `not_to`' do
wrapped.to_not receive(:foo)
expect_fast_failure_from(receiver, /expected: 0 times.*received: 1 time/m) do
receiver.foo
end
end
it 'allows the caller to constrain the received arguments' do
wrapped.not_to receive(:foo).with(:a)
def receiver.method_missing(*); end # a poor man's stub...
expect {
receiver.foo(:b)
}.not_to raise_error
expect_fast_failure_from(receiver, /expected: 0 times.*received: 1 time/m) do
receiver.foo(:a)
end
end
it 'prevents confusing double-negative expressions involving `never`' do
expect {
wrapped.not_to receive(:foo).never
}.to raise_error(/trying to negate it again/)
expect {
wrapped.to_not receive(:foo).never
}.to raise_error(/trying to negate it again/)
end
end
shared_examples "resets partial mocks cleanly" do
let(:klass) { Struct.new(:foo) }
let(:object) { klass.new :bar }
it "removes the method double" do
target.to receive(:foo).and_return(:baz)
expect { reset object }.to change { object.foo }.from(:baz).to(:bar)
end
end
shared_examples "resets partial mocks of any instance cleanly" do
let(:klass) { Struct.new(:foo) }
let(:object) { klass.new :bar }
it "removes the method double" do
target.to receive(:foo).and_return(:baz)
expect {
verify_all
}.to change { object.foo }.from(:baz).to(:bar)
end
end
shared_examples "handles frozen objects cleanly" do
let(:klass) { Struct.new(:foo) }
let(:object) { klass.new :bar }
context "when adding the method double" do
it "raises clear error" do
object.freeze
expect {
target.to receive(:foo).and_return(:baz)
}.to raise_error(ArgumentError, /Cannot proxy frozen objects/)
end
end
context "when removing the method double" do
before do
if RUBY_VERSION < "2.2" && RUBY_VERSION >= "2.0" && RSpec::Support::Ruby.mri?
pending "Does not work on 2.0-2.1 because frozen structs can have methods restored"
end
end
it "warns about being unable to remove the method double" do
target.to receive(:foo).and_return(:baz)
expect_warning_without_call_site(/rspec-mocks was unable to restore the original `foo` method on #{object.inspect}/)
object.freeze
reset object
end
it "includes the spec location in the warning" do
line = __LINE__ - 1
target.to receive(:foo).and_return(:baz)
expect_warning_without_call_site(/#{RSpec::Core::Metadata.relative_path(__FILE__)}:#{line}/)
object.freeze
reset object
end
end
context "with fake frozen object" do
let(:klass) { Struct.new(:foo, :frozen?, :freeze) }
let(:object) { klass.new :bar, true }
it "allows the caller to configure how the subject responds" do
object.freeze
target.to receive(:foo).and_return(5)
expect(object.foo).to eq(5)
expect { reset object }.to change { object.foo }.from(5).to(:bar)
end
end
end
describe "allow(...).to receive" do
it_behaves_like "an expect syntax allowance" do
let(:receiver) { double }
let(:wrapped) { allow(receiver) }
end
it_behaves_like "resets partial mocks cleanly" do
let(:target) { allow(object) }
end
it_behaves_like "handles frozen objects cleanly" do
let(:target) { allow(object) }
end
context 'ordered with receive counts' do
specify 'is not supported' do
a_dbl = double
expect_warning_with_call_site(__FILE__, __LINE__ + 1)
allow(a_dbl).to receive(:one).ordered
end
end
context 'on a class method, from a class with subclasses' do
let(:superclass) { Class.new { def self.foo; "foo"; end }}
let(:subclass_redef) { Class.new(superclass) { def self.foo; ".foo."; end }}
let(:subclass_deleg) { Class.new(superclass) { def self.foo; super.upcase; end }}
let(:subclass_asis) { Class.new(superclass) }
context 'if the method is redefined in the subclass' do
it 'does not stub the method in the subclass' do
allow(superclass).to receive(:foo) { "foo!!" }
expect(superclass.foo).to eq "foo!!"
expect(subclass_redef.foo).to eq ".foo."
end
end
context 'if the method is not redefined in the subclass' do
it 'stubs the method in the subclass' do
allow(superclass).to receive(:foo) { "foo!!" }
expect(superclass.foo).to eq "foo!!"
expect(subclass_asis.foo).to eq "foo!!"
end
end
it 'creates stub which can be called using `super` in a subclass' do
allow(superclass).to receive(:foo) { "foo!!" }
expect(subclass_deleg.foo).to eq "FOO!!"
end
it 'can stub the same method simultaneously in the superclass and subclasses' do
allow(subclass_redef).to receive(:foo) { "__foo__" }
allow(superclass).to receive(:foo) { "foo!!" }
allow(subclass_deleg).to receive(:foo) { "$$foo$$" }
expect(subclass_redef.foo).to eq "__foo__"
expect(superclass.foo).to eq "foo!!"
expect(subclass_deleg.foo).to eq "$$foo$$"
end
end
end
describe "allow(...).not_to receive" do
it_behaves_like "an expect syntax negative allowance" do
let(:wrapped) { allow(double) }
end
end
describe "allow_any_instance_of(...).to receive" do
it_behaves_like "an expect syntax allowance" do
let(:klass) { Class.new }
let(:wrapped) { allow_any_instance_of(klass) }
let(:receiver) { klass.new }
end
it_behaves_like "resets partial mocks of any instance cleanly" do
let(:target) { allow_any_instance_of(klass) }
end
end
describe "allow_any_instance_of(...).not_to receive" do
it_behaves_like "an expect syntax negative allowance" do
let(:wrapped) { allow_any_instance_of(Class.new) }
end
end
describe "expect(...).to receive" do
it_behaves_like "an expect syntax expectation", :allow_other_matchers do
let(:receiver) { double }
let(:wrapped) { expect(receiver) }
context "when a message is not received" do
it 'sets up a message expectation that formats argument matchers correctly' do
wrapped.to receive(:foo).with an_instance_of Float
expect { verify_all }.to(
raise_error(/expected: 1 time with arguments: \(an instance of Float\)\n\s+received: 0 times$/)
)
end
end
context "when a message is received the wrong number of times" do
it "sets up a message expectation that formats argument matchers correctly" do
wrapped.to receive(:foo).with(anything, hash_including(:bar => anything))
receiver.foo(1, :bar => 2)
receiver.foo(1, :bar => 3)
expect { verify_all }.to(
raise_error(/received: 2 times with arguments: \(anything, hash_including\(:bar=>"anything"\)\)$/)
)
end
end
end
it_behaves_like "resets partial mocks cleanly" do
let(:target) { expect(object) }
end
it_behaves_like "handles frozen objects cleanly" do
let(:target) { expect(object) }
end
context "ordered with receive counts" do
let(:dbl) { double(:one => 1, :two => 2) }
it "passes with exact receive counts when the ordering is correct" do
expect(dbl).to receive(:one).twice.ordered
expect(dbl).to receive(:two).once.ordered
dbl.one
dbl.one
dbl.two
end
it "fails with exact receive counts when the ordering is incorrect" do
expect {
expect(dbl).to receive(:one).twice.ordered
expect(dbl).to receive(:two).once.ordered
dbl.one
dbl.two
dbl.one
}.to raise_error(/out of order/)
reset_all
end
it "passes with at least when the ordering is correct" do
expect(dbl).to receive(:one).at_least(2).times.ordered
expect(dbl).to receive(:two).once.ordered
dbl.one
dbl.one
dbl.one
dbl.two
end
it "fails with at least when the ordering is incorrect", :ordered_and_vague_counts_unsupported do
expect {
expect(dbl).to receive(:one).at_least(2).times.ordered
expect(dbl).to receive(:two).once.ordered
dbl.one
dbl.two
}.to fail
reset_all
end
it "passes with at most when the ordering is correct" do
expect(dbl).to receive(:one).at_most(2).times.ordered
expect(dbl).to receive(:two).once.ordered
dbl.one
dbl.two
end
it "fails with at most when the ordering is incorrect", :ordered_and_vague_counts_unsupported do
expect {
expect(dbl).to receive(:one).at_most(2).times.ordered
expect(dbl).to receive(:two).once.ordered
dbl.one
dbl.one
dbl.one
dbl.two
}.to fail
reset_all
end
it 'does not result in infinite recursion when `respond_to?` is stubbed' do
# Setting a method expectation causes the method to be proxied
# RSpec may call #respond_to? when processing a failed expectation
# If those internal calls go to the proxied method, that could
# result in another failed expectation error, causing infinite loop
expect {
obj = Object.new
expect(obj).to receive(:respond_to?).with('something highly unlikely')
obj.respond_to?(:not_what_we_wanted)
}.to raise_error(/received :respond_to\? with unexpected arguments/)
reset_all
end
end
end
describe "expect_any_instance_of(...).to receive" do
it_behaves_like "an expect syntax expectation", :does_not_report_line_num do
let(:klass) { Class.new }
let(:wrapped) { expect_any_instance_of(klass) }
let(:receiver) { klass.new }
it 'sets up a message expectation that formats argument matchers correctly' do
wrapped.to receive(:foo).with an_instance_of Float
expect { verify_all }.to raise_error(/should have received the following message\(s\) but didn't/)
end
end
it_behaves_like "resets partial mocks of any instance cleanly" do
let(:target) { expect_any_instance_of(klass) }
end
end
describe "expect(...).not_to receive" do
it_behaves_like "an expect syntax negative expectation" do
let(:receiver) { double }
let(:wrapped) { expect(receiver) }
end
end
describe "expect_any_instance_of(...).not_to receive" do
it_behaves_like "an expect syntax negative expectation" do
let(:klass) { Class.new }
let(:wrapped) { expect_any_instance_of(klass) }
let(:receiver) { klass.new }
end
end
it 'has a description before being matched' do
matcher = receive(:foo)
expect(matcher.description).to eq("receive foo")
end
shared_examples "using rspec-mocks in another test framework" do
it 'can use the `expect` syntax' do
dbl = double
framework.new.instance_exec do
expect(dbl).to receive(:foo).and_return(3)
end
expect(dbl.foo).to eq(3)
end
it 'expects the method to be called when `expect` is used' do
dbl = double
framework.new.instance_exec do
expect(dbl).to receive(:foo)
end
expect { verify dbl }.to fail
end
it 'supports `expect(...).not_to receive`' do
expect_fast_failure_from(double) do |dbl|
framework.new.instance_exec do
expect(dbl).not_to receive(:foo)
end
dbl.foo
end
end
it 'supports `expect(...).to_not receive`' do
expect_fast_failure_from(double) do |dbl|
framework.new.instance_exec do
expect(dbl).to_not receive(:foo)
end
dbl.foo
end
end
end
context "when used in a test framework without rspec-expectations" do
let(:framework) do
Class.new do
include RSpec::Mocks::ExampleMethods
def eq(_)
double("MyMatcher")
end
end
end
it_behaves_like "using rspec-mocks in another test framework"
it 'cannot use `expect` with another matcher' do
expect {
framework.new.instance_exec do
expect(3).to eq(3)
end
}.to raise_error(/only the `receive`, `have_received` and `receive_messages` matchers are supported with `expect\(...\).to`/)
end
it 'can toggle the available syntax' do
expect(framework.new).to respond_to(:expect)
RSpec::Mocks.configuration.syntax = :should
expect(framework.new).not_to respond_to(:expect)
RSpec::Mocks.configuration.syntax = :expect
expect(framework.new).to respond_to(:expect)
end
after { RSpec::Mocks.configuration.syntax = :expect }
end
context "when rspec-expectations is included in the test framework first" do
before do
# the examples here assume `expect` is define in RSpec::Matchers...
expect(RSpec::Matchers.method_defined?(:expect)).to be_truthy
end
let(:framework) do
Class.new do
include RSpec::Matchers
include RSpec::Mocks::ExampleMethods
end
end
it_behaves_like "using rspec-mocks in another test framework"
it 'can use `expect` with any matcher' do
framework.new.instance_exec do
expect(3).to eq(3)
end
end
it 'with a nonsense allowance it fails with a reasonable error message' do
expect {
allow(true).not_to be_nil
}.to raise_error(start_with("`allow(...).not_to be_nil` is not supported since it doesn't really make sense"))
end
end
context "when rspec-expectations is included in the test framework last" do
before do
# the examples here assume `expect` is define in RSpec::Matchers...
expect(RSpec::Matchers.method_defined?(:expect)).to be_truthy
end
let(:framework) do
Class.new do
include RSpec::Mocks::ExampleMethods
include RSpec::Matchers
end
end
it_behaves_like "using rspec-mocks in another test framework"
it 'can use `expect` with any matcher' do
framework.new.instance_exec do
expect(3).to eq(3)
end
end
end
end
end
end
|
module FlattenArray
module_function
def flatten(arr)
arr.reduce([]) do |acc, el|
el.respond_to?(:flatten) ? acc += flatten(el) : acc << el
end.reject(&:nil?)
end
end
module BookKeeping
VERSION = 1
end
|
pain_descriptors = [
'burning',
'aching',
'stinging',
'throbbing',
'itching',
'numbing',
'pins and needles',
'pulling',
'sharp',
'jabbing',
'shooting',
'electric',
'mechanical',
'thermal',
'abrupt',
'increasing',
'decreasing',
'with exercise',
'with movement'
]
family_history = Topic.create!(
name: 'family history',
topic_type: 'root category'
)
Topic.create!(
name: 'parent',
topic_type: 'family member'
).move_to_child_of(family_history)
Topic.create!(
name: 'sibling',
topic_type: 'family member'
).move_to_child_of(family_history)
Topic.create!(
name: 'child',
topic_type: 'family member'
).move_to_child_of(family_history)
Topic.create!(
name: 'grandparent',
topic_type: 'family member'
).move_to_child_of(family_history)
Topic.create!(
name: 'grandchild',
topic_type: 'family member'
).move_to_child_of(family_history)
## END FAMILY HISTORY (xls 11) ##
## BEGIN LIFESTYLE ##
lifestyle = Topic.create!(
name: 'lifestyle',
topic_type: 'root category'
)
Topic.create!(
name: 'tobacco',
topic_type: 'measurement',
units_of_measurement: %w[current past never]
).move_to_child_of(lifestyle)
Topic.create!(
name: 'ETOH',
topic_type: 'measurement',
units_of_measurement: ['drinks per day']
).move_to_child_of(lifestyle)
Topic.create!(
name: 'exercise',
topic_type: 'measurement',
units_of_measurement: %w[none mild moderate strenuous competitive]
).move_to_child_of(lifestyle)
## END LIFESTYLE ##
## BEGIN GENETICS (xls 13) ##
genetics = Topic.create!(
name: 'genetics',
topic_type: 'root category'
)
clinical_diagnosis = Topic.create!(
name: 'clinical diagnosis',
topic_type: 'genetic test'
).move_to_child_of(genetics)
mutation = Topic.create!(
name: 'mutation',
topic_type: 'genetic test'
).move_to_child_of(genetics)
fbn1 = Topic.create!(
name: 'FBN1',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'TGFBR1',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'TGFBR2',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'SMAD3',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'TGFB2',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'ACTA2',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'PRKG1',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'MYH11',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'MYLK',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'FBLN4',
topic_type: 'genetic test'
).move_to_child_of(mutation)
Topic.create!(
name: 'COL3A1',
topic_type: 'genetic test'
).move_to_child_of(mutation)
## END GENETICS (xls 28) ##
## BEGIN MEDICATIONS (xls 41) ##
meds = Topic.create!(
name: 'medication',
topic_type: 'root category'
)
triptans = Topic.create!(
name: 'triptans',
topic_type: 'medication'
).move_to_child_of(meds)
prophylaxis = Topic.create!(
name: 'prophylaxis',
topic_type: 'medication'
).move_to_child_of(meds)
antiepileptics = Topic.create!(
name: 'antiepileptics',
topic_type: 'medication'
).move_to_child_of(prophylaxis)
calcium_channel_blocker = Topic.create!(
name: 'Ca-blockers',
topic_type: 'medication'
).move_to_child_of(prophylaxis)
tricyclics = Topic.create!(
name: 'tricyclics',
topic_type: 'medication'
).move_to_child_of(prophylaxis)
beta_blockers = Topic.create!(
name: 'beta-blockers',
topic_type: 'medication'
).move_to_child_of(meds)
Topic.create!(
name: 'atenolol',
topic_type: 'medication'
).move_to_child_of(beta_blockers)
Topic.create!(
name: 'metoprolol',
topic_type: 'medication'
).move_to_child_of(beta_blockers)
Topic.create!(
name: 'propranolol',
topic_type: 'medication'
).move_to_child_of(beta_blockers)
other_beta = Topic.create!(
name: 'other',
topic_type: 'medication'
).move_to_child_of(beta_blockers)
Topic.create!(
name: 'carvedilol',
topic_type: 'medication'
).move_to_child_of(other_beta)
Topic.create!(
name: 'betaxolol',
topic_type: 'medication'
).move_to_child_of(other_beta)
Topic.create!(
name: 'labetalol',
topic_type: 'medication'
).move_to_child_of(other_beta)
arb = Topic.create!(
name: 'ARB',
topic_type: 'medication'
).move_to_child_of(meds)
Topic.create!(
name: 'losartan',
topic_type: 'medication'
).move_to_child_of(arb)
Topic.create!(
name: 'valsartan',
topic_type: 'medication'
).move_to_child_of(arb)
Topic.create!(
name: 'irbesartan',
topic_type: 'medication'
).move_to_child_of(arb)
Topic.create!(
name: 'telmisartan',
topic_type: 'medication'
).move_to_child_of(arb)
Topic.create!(
name: 'candesartan',
topic_type: 'medication'
).move_to_child_of(arb)
other_arb = Topic.create!(
name: 'other',
topic_type: 'medication'
).move_to_child_of(arb)
calcium_channel_blocker = Topic.create!(
name: 'calcium channel blocker',
topic_type: 'medication'
).move_to_child_of(meds)
Topic.create!(
name: 'verapamil',
topic_type: 'medication'
).move_to_child_of(calcium_channel_blocker)
Topic.create!(
name: 'diltiazem',
topic_type: 'medication'
).move_to_child_of(calcium_channel_blocker)
Topic.create!(
name: 'amlodipine',
topic_type: 'medication'
).move_to_child_of(calcium_channel_blocker)
Topic.create!(
name: 'nifedipine',
topic_type: 'medication'
).move_to_child_of(calcium_channel_blocker)
other_calcium_channel_blocker = Topic.create!(
name: 'other',
topic_type: 'medication'
).move_to_child_of(calcium_channel_blocker)
ace_inhibitor = Topic.create!(
name: 'ACE-inhibitor',
topic_type: 'medication'
).move_to_child_of(meds)
Topic.create!(
name: 'lisinopril',
topic_type: 'medication'
).move_to_child_of(ace_inhibitor)
Topic.create!(
name: 'enalapril',
topic_type: 'medication'
).move_to_child_of(ace_inhibitor)
Topic.create!(
name: 'captopril',
topic_type: 'medication'
).move_to_child_of(ace_inhibitor)
other_ace = Topic.create!(
name: 'other',
topic_type: 'medication'
).move_to_child_of(ace_inhibitor)
Topic.create!(
name: 'accupril',
topic_type: 'medication'
).move_to_child_of(other_ace)
Topic.create!(
name: 'perindopril',
topic_type: 'medication'
).move_to_child_of(other_ace)
Topic.create!(
name: 'trandolapril',
topic_type: 'medication'
).move_to_child_of(other_ace)
## END MEDICATIONS (xls 61)
## BEGIN VITALS (xls 63) ##
vitals = Topic.create!(
name: 'vitals',
topic_type: 'root category'
)
Topic.create!(
name: 'weight',
topic_type: 'vital',
min_value: 0,
max_value: 500,
step: 0.1,
units_of_measurement: %w[kg lb]
).move_to_child_of(vitals)
Topic.create!(
name: 'height',
topic_type: 'vital',
min_value: 0,
max_value: 250,
step: 0.01,
units_of_measurement: %w[m in]
).move_to_child_of(vitals)
Topic.create!(
name: 'blood pressure',
topic_type: 'vital',
min_value: 0,
max_value: 250,
step: 1,
units_of_measurement: %w[mmHg]
).move_to_child_of(vitals)
Topic.create!(
name: 'heart rate',
topic_type: 'vital',
min_value: 10,
max_value: 200,
step: 1,
units_of_measurement: %w[bpm]
).move_to_child_of(vitals)
Topic.create!(
name: 'temperature',
topic_type: 'vital',
min_value: 0.0,
max_value: 120.0,
step: 0.1,
units_of_measurement: %w[°C °F]
).move_to_child_of(vitals)
## END VITALS (xls 66) ##
## BEGIN MORPHOLOGY (xls 68) ##
morphology = Topic.create!(
name: 'morphology/physical findings',
topic_type: 'root category'
)
Topic.create!(
name: 'arm span',
topic_type: 'measurement',
min_value: 0,
max_value: 250,
step: 0.01,
units_of_measurement: %w[m in]
).move_to_child_of(morphology)
Topic.create!(
name: 'lower segment',
topic_type: 'measurement',
min_value: 0,
max_value: 250,
step: 0.01,
units_of_measurement: %w[m in]
).move_to_child_of(morphology)
Topic.create!(
name: 'iridodenesis',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'blue sclera',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'sunken eyes',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'hypertelorism',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'dolichocephaly',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'malar hypoplasia',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'retrognathia',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
high_arched_palate = Topic.create!(
name: 'high arched palate',
topic_type: 'diagnosis',
descriptors: ['palate spreader', 'no palate spreader']
).move_to_child_of(morphology)
narrow_palate = Topic.create!(
name: 'narrow palate',
topic_type: 'diagnosis',
descriptors: ['repaired', 'not repaired']
).move_to_child_of(morphology)
cleft_palate = Topic.create!(
name: 'cleft palate',
topic_type: 'diagnosis',
descriptors: ['repaired', 'not repaired']
).move_to_child_of(morphology)
Topic.create!(
name: 'bifid uvula',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'broad uvula',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
dental_crowding = Topic.create!(
name: 'dental crowding',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'orthodontia',
topic_type: 'procedure'
).move_to_child_of(morphology)
Topic.create!(
name: 'teeth extraction',
topic_type: 'procedure'
).move_to_child_of(morphology)
Topic.create!(
name: 'craniosynostosis',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
pe_morph = Topic.create!(
name: 'pectus excavatum',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
pc_morph = Topic.create!(
name: 'pectus carinatum',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
ap_morph = Topic.create!(
name: 'asymmetric pectus',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
kypho = Topic.create!(
name: 'lumbar kyphoscoliosis',
topic_type: 'measurement',
units_of_measurement: %w[degrees]
).move_to_child_of(morphology)
thoracic_kypho = Topic.create!(
name: 'thoracic kyphoscoliosis',
topic_type: 'diagnosis',
units_of_measurement: %w[degrees]
).move_to_child_of(kypho)
Topic.create!(
name: 'spondylolisthesis',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'loss of lumbar lordosis',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'thumb sign',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'wrist sign',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'small joint hypermobility',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'arachnodactyly',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'cubitus valgus',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
Topic.create!(
name: 'elbow contracture',
topic_type: 'diagnosis'
).move_to_child_of(morphology)
## END MORPHOLOGY (xls 123) ##
## BEGIN AORTIC MEASUREMENTS (xls 126) ##
cardio_meas = Topic.create!(
name: 'aortic imaging',
topic_type: 'root category'
)
Topic.create!(
name: 'aortic root',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 7.0,
step: 0.1,
units_of_measurement: %w[cm]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'ascending aortic',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 7.0,
step: 0.1,
units_of_measurement: %w[cm]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'transverse arch',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 7.0,
step: 0.1,
units_of_measurement: %w[cm]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'descending thoracic aorta',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 7.0,
step: 0.1,
units_of_measurement: %w[cm]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'suprarenal abdominal aorta',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 7.0,
step: 0.1,
units_of_measurement: %w[cm]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'infrarenal abdominal aorta',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 7.0,
step: 0.1,
units_of_measurement: %w[cm]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'aortic annulus',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 7.0,
step: 0.1,
units_of_measurement: %w[cm]
).move_to_child_of(cardio_meas)
## END AORTA MEASUREMENTS (xls 132) ##
cardio = Topic.create!(
name: 'cardiovascular',
topic_type: 'root category'
)
## BEGIN 1-DEPTH TOPICS (xls 134) ##
Topic.create!(
name: 'systolic function',
topic_type: 'heart_measurement',
units_of_measurement: %w[normal mild moderate severe]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'LVIDd',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 10.0,
step: 0.1,
units_of_measurement: %w[cm],
descriptors: %w[normal enlarged]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'LVIDs',
topic_type: 'heart_measurement',
min_value: 1.0,
max_value: 8.0,
step: 0.1,
units_of_measurement: %w[cm],
descriptors: %w[normal enlarged]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'EF',
topic_type: 'heart_measurement',
min_value: 20.0,
max_value: 100.0,
step: 1.0,
units_of_measurement: %w[%],
descriptors: %w[normal enlarged]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'FS',
topic_type: 'heart_measurement',
min_value: 0.0,
max_value: 100.0,
step: 1.0,
units_of_measurement: %w[%],
descriptors: %w[normal enlarged]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'mitral valve morphology',
topic_type: 'heart_measurement',
units_of_measurement: ['prolapse (anterior)', 'prolapse (posterior)', 'myxomatous']
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'mitral regurgitation severity',
topic_type: 'heart_measurement',
min_value: 0,
max_value: 100,
step: 1,
units_of_measurement: %w[%]
).move_to_child_of(cardio_meas)
## END 1-DEPTH TOPICS (xls 140)##
## BEGIN SHALLOW TOPICS (xls 142) ##
aortic_valve_morph = Topic.create!(
name: 'aortic valve morphology',
topic_type: 'heart_measurement',
units_of_measurement: %w[trileaflet bicuspid unicuspid Sievers-0 Sievers-1 Sievers-2]
).move_to_child_of(cardio)
Topic.create!(
name: 'regurgitation',
topic_type: 'heart_measurement',
units_of_measurement: %w[none mild moderate severe]
).move_to_child_of(aortic_valve_morph)
aortic_stenosis = Topic.create!(
name: 'aortic stenosis',
topic_type: 'heart_measurement',
units_of_measurement: %w[none mild moderate severe]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'mean gradient',
topic_type: 'heart_measurement',
min_value: 20,
max_value: 100,
step: 1,
units_of_measurement: %w[mmHg]
).move_to_child_of(aortic_stenosis)
Topic.create!(
name: 'valve area',
topic_type: 'heart_measurement',
min_value: 0.5,
max_value: 3.0,
step: 0.1,
units_of_measurement: %w[cm2]
).move_to_child_of(aortic_stenosis)
Topic.create!(
name: 'aortic insufficiency severity',
topic_type: 'heart_measurement',
min_value: 0,
max_value: 100,
step: 1,
units_of_measurement: %w[%]
).move_to_child_of(cardio_meas)
Topic.create!(
name: 'tricuspid regurgitation severity',
topic_type: 'heart_measurement',
min_value: 0,
max_value: 100,
step: 1,
units_of_measurement: %w[%]
).move_to_child_of(cardio_meas)
## END SHALLOW TOPICS (xls 147) %>
## BEGIN SHALLOW DISSECTIONS (xls 149) ##
# aortic_dissection = Topic.create!(
# name: 'aortic dissection',
# topic_type: 'diagnosis'
# ).move_to_child_of(cardio)
# Topic.create!(
# name: 'aortic root',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
# Topic.create!(
# name: 'ascending aorta',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
# Topic.create!(
# name: 'arch',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
# Topic.create!(
# name: 'descending thoracic',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
# Topic.create!(
# name: 'suprarenal abdominal',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
# Topic.create!(
# name: 'infrarenal abdominal',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
# ## END SHALLOW DISSECTIONS (xls 154) ##
#
# iliac = Topic.create!(
# name: 'iliac',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
#
# Topic.create!(
# name: 'right',
# topic_type: 'diagnosis'
# ).move_to_child_of(iliac)
#
# Topic.create!(
# name: 'left',
# topic_type: 'diagnosis'
# ).move_to_child_of(iliac)
#
# renal = Topic.create!(
# name: 'renal',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
#
# Topic.create!(
# name: 'right',
# topic_type: 'diagnosis'
# ).move_to_child_of(renal)
#
# Topic.create!(
# name: 'left',
# topic_type: 'diagnosis'
# ).move_to_child_of(renal)
#
# ## BEGIN SMA DISSECTION (xls 161) ##
# sma = Topic.create!(
# name: 'SMA',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
#
# celiac = Topic.create!(
# name: 'celiac',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
#
# innominate = Topic.create!(
# name: 'innominate',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
#
#
# left_carotid = Topic.create!(
# name: 'left carotid',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
#
# left_subclavian = Topic.create!(
# name: 'left subclavian',
# topic_type: 'diagnosis'
# ).move_to_child_of(aortic_dissection)
dissection = Topic.create!(
name: 'dissection',
topic_type: 'dissection'
).move_to_child_of(cardio)
## BEGIN ROOT REPLACEMENT (xls 177) ##
aortic_surgery = Topic.create!(
name: 'aortic surgery',
topic_type: 'procedure'
).move_to_child_of(cardio)
root_replacement = Topic.create!(
name: 'root replacement',
topic_type: 'procedure'
).move_to_child_of(aortic_surgery)
cvg = Topic.create!(
name: 'CVG',
topic_type: 'procedure',
descriptors: ['mechanical prosthesis', 'bioprosthesis']
).move_to_child_of(root_replacement)
valve_sparing = Topic.create!(
name: 'valve sparing',
topic_type: 'procedure',
descriptors: ['Tirone-David', 'TD-V Smod', 'Valsalva Graft', 'Yacoub']
).move_to_child_of(root_replacement)
Topic.create!(
name: 'supracoronary',
topic_type: 'procedure'
).move_to_child_of(root_replacement)
Topic.create!(
name: 'honograft',
topic_type: 'procedure'
).move_to_child_of(root_replacement)
Topic.create!(
name: 'freestyle prosthesis',
topic_type: 'procedure'
).move_to_child_of(root_replacement)
## END ROOT REPLACEMENT (xls 184) ##
## BEGIN ASCENDING REPLACEMENT (xls 185) ##
asc_repl = Topic.create!(
name: 'ascending replacement',
topic_type: 'procedure',
descriptors: ['clamped', 'open distal anstomosis']
).move_to_child_of(aortic_surgery)
Topic.create!(
name: 'clamped',
topic_type: 'procedure'
).move_to_child_of(asc_repl)
Topic.create!(
name: 'open distal anstomosis',
topic_type: 'procedure'
).move_to_child_of(asc_repl)
## END ASCENDING REPLACEMENT (xls 186) ##
## BEGIN ARCH REPLACEMENT (xls 187) ##
arch_repl = Topic.create!(
name: 'arch replacement',
topic_type: 'procedure'
).move_to_child_of(aortic_surgery)
## END ARCH REPLACEMENT (xls 189) ##
## BEGIN SHALLOW REPLACEMENTS (xls 187) ##
Topic.create!(
name: 'descending thoracic aorta replacement',
topic_type: 'procedure'
).move_to_child_of(aortic_surgery)
Topic.create!(
name: 'suprarenal aorta replacement',
topic_type: 'procedure'
).move_to_child_of(aortic_surgery)
Topic.create!(
name: 'infrarenal aorta replacement',
topic_type: 'procedure'
).move_to_child_of(aortic_surgery)
## END SHALLOW REPLACEMENTS (xls 189) ##
## BEGIN STENT GRAFT (xls 194) ##
Topic.create!(
name: 'stent graft',
topic_type: 'procedure',
descriptors: ['thoracic', 'endoleak', 'suprarenal', 'infrarenal', 'right iliac', 'left iliac', 'right subclavian', 'left sublcavian']
).move_to_child_of(cardio)
## END STENT GRAFT (xls 200) ##
## BEGIN MITRAL VALVE SURGERY (xls 202) ##
mitral_valve_surgery = Topic.create!(
name: 'mitral valve surgery',
topic_type: 'procedure'
).move_to_child_of(cardio)
mitral_valve_repair = Topic.create!(
name: 'mitral valve repair',
topic_type: 'procedure',
descriptors: ['ring only', 'leaflet repair']
).move_to_child_of(mitral_valve_surgery)
mitral_valve_replacement = Topic.create!(
name: 'mitral valve replacement',
topic_type: 'procedure',
descriptors: ['mechanical prosthesis', 'bioprosthetic']
).move_to_child_of(mitral_valve_surgery)
## END MITRAL VALVE SURGERY (xls 205) ##
Topic.create!(
name: 'arrhythmia',
topic_type: 'diagnosis',
descriptors: ['PVC', 'PAC', 'afib/aflutter', 'VT/VF', 'sudden death', 'AICD']
).move_to_child_of(cardio)
## BEGIN VARICOSE VEINS (xls 214) ##
legs = Topic.create!(
name: 'legs',
topic_type: 'middle'
).move_to_child_of(cardio)
varicose = Topic.create!(
name: 'varicose veins',
topic_type: 'diagnosis'
).move_to_child_of(legs)
Topic.create!(
name: 'edema',
topic_type: 'diagnosis'
).move_to_child_of(legs)
Topic.create!(
name: 'sclerotherapy/stripping',
topic_type: 'procedure'
).move_to_child_of(legs)
## END VARICOSE VEINS (xls 215) ##
## BEGIN CORONARY DISEASE (xls 217) ##
coronary_disease = Topic.create!(
name: 'coronary disease',
topic_type: 'diagnosis'
).move_to_child_of(cardio)
Topic.create!(
name: 'angina',
topic_type: 'diagnosis'
).move_to_child_of(coronary_disease)
Topic.create!(
name: 'myocardial infarction',
topic_type: 'diagnosis'
).move_to_child_of(coronary_disease)
Topic.create!(
name: 'angioplasty/stent',
topic_type: 'procedure'
).move_to_child_of(coronary_disease)
Topic.create!(
name: 'CABG',
topic_type: 'procedure'
).move_to_child_of(coronary_disease)
## END CORONARY DISEASE (xls 220) ##
## BEGIN SYMPTOMS (xls 222) ##
symptoms = Topic.create!(
name: 'symptoms',
topic_type: 'diagnosis'
).move_to_child_of(cardio)
Topic.create!(
name: 'chest pain',
topic_type: 'diagnosis',
descriptors: pain_descriptors
).move_to_child_of(symptoms)
Topic.create!(
name: 'dyspnea on exertion',
topic_type: 'diagnosis'
).move_to_child_of(symptoms)
Topic.create!(
name: 'palpitations',
topic_type: 'diagnosis',
descriptors: ['lightheaded', 'shortness of breath', 'syncope', 'skipped beats', 'strong beats', 'heart racing', 'extra beats', 'constant', 'fainting']
).move_to_child_of(symptoms)
Topic.create!(
name: 'lightheadedness',
topic_type: 'diagnosis'
).move_to_child_of(symptoms)
Topic.create!(
name: 'edema',
topic_type: 'diagnosis',
descriptors: ['at night', 'left leg', 'right leg', 'left arm', 'right arm', 'face', 'better in AM', 'provoked by salt', 'provoked by dependence']
).move_to_child_of(symptoms)
## END SYMPTOMS (xls 226) ##
## BEGIN SHALLOW PULMONARY (xls 228) ##
pulmonary = Topic.create!(
name: 'pulmonary',
topic_type: 'root category'
)
Topic.create!(
name: 'shortness of breath',
topic_type: 'diagnosis',
descriptors: ['at rest', 'walking', 'running', 'up stairs', 'fainting', 'cough', 'wheezing']
).move_to_child_of(pulmonary)
Topic.create!(
name: 'emphysema',
topic_type: 'diagnosis'
).move_to_child_of(pulmonary)
Topic.create!(
name: 'CT/CXR',
topic_type: 'measurement',
units_of_measurement: %w[cm]
).move_to_child_of(pulmonary)
Topic.create!(
name: 'TLC',
topic_type: 'measurement',
units_of_measurement: %w[cm]
).move_to_child_of(pulmonary)
Topic.create!(
name: 'PFT',
topic_type: 'measurement',
units_of_measurement: %w[cm]
).move_to_child_of(pulmonary)
Topic.create!(
name: 'FEV1',
topic_type: 'measurement',
units_of_measurement: %w[cm]
).move_to_child_of(pulmonary)
Topic.create!(
name: 'restrictive lung disease',
topic_type: 'diagnosis'
).move_to_child_of(pulmonary)
Topic.create!(
name: 'asthma',
topic_type: 'diagnosis'
).move_to_child_of(pulmonary)
Topic.create!(
name: 'bronchodilator response',
topic_type: 'measurement',
units_of_measurement: %w[cm]
).move_to_child_of(pulmonary)
## END SHALLOW PULMONARY (xls 233) ##
## BEGIN PNEUMOTHORAX (xls 234)##
pneumothorax = Topic.create!(
name: 'pneumothorax',
topic_type: 'procedure',
descriptors: ['chest tube', 'pleurodesis', 'VATS']
).move_to_child_of(pulmonary)
Topic.create!(
name: 'blebs',
topic_type: 'diagnosis'
).move_to_child_of(pneumothorax)
## END PNEUMOTHORAX (xls 237) ##
## BEGIN SHALLOW PULMONARY LAST (xls 238) ##
sleep_apnea = Topic.create!(
name: 'sleep apnea',
topic_type: 'diagnosis'
).move_to_child_of(pulmonary)
Topic.create!(
name: 'CPAP',
topic_type: 'medication'
).move_to_child_of(pulmonary)
Topic.create!(
name: 'bronchodilators',
topic_type: 'medication'
).move_to_child_of(pulmonary)
Topic.create!(
name: 'inhaled steroids',
topic_type: 'medication'
).move_to_child_of(pulmonary)
Topic.create!(
name: 'systemic steroids',
topic_type: 'medication'
).move_to_child_of(pulmonary)
## END SHALLOW PULMONARY LAST (xls 243) ##
## BEGIN ORTHOPEDIC BACK (xls 245) ##
ortho = Topic.create!(
name: 'orthopedic',
topic_type: 'root category'
)
back = Topic.create!(
name: 'back',
topic_type: 'middle'
).move_to_child_of(ortho)
scolio = Topic.create!(
name: 'scoliosis',
topic_type: 'middle'
).move_to_child_of(back)
Topic.create!(
name: 'spondylolisthesis',
topic_type: 'diagnosis'
).move_to_child_of(back)
Topic.create!(
name: 'thoracic scoliosis',
topic_type: 'diagnosis'
).move_to_child_of(scolio)
Topic.create!(
name: 'lumbar scoliosis',
topic_type: 'diagnosis'
).move_to_child_of(scolio)
bracing = Topic.create!(
name: 'bracing',
topic_type: 'procedure'
).move_to_child_of(back)
harr = Topic.create!(
name: 'Harrington Rods',
topic_type: 'procedure'
).move_to_child_of(back)
physio = Topic.create!(
name: 'physical therapy',
topic_type: 'procedure'
).move_to_child_of(back)
fusion = Topic.create!(
name: 'fusion',
topic_type: 'procedure'
).move_to_child_of(back)
## END ORTHOPEDIC BACK (xls 253) ##
## BEGIN PECTUS (xls 254) ##
pectus = Topic.create!(
name: 'pectus',
topic_type: 'middle'
).move_to_child_of(ortho)
Topic.create!(
name: 'pectus excavatum',
topic_type: 'diagnosis'
).move_to_child_of(pectus)
Topic.create!(
name: 'pectus carinatum',
topic_type: 'diagnosis'
).move_to_child_of(pectus)
Topic.create!(
name: 'asymmetric pectus',
topic_type: 'diagnosis'
).move_to_child_of(pectus)
ravitch = Topic.create!(
name: 'Ravitch procedure',
topic_type: 'procedure'
).move_to_child_of(ortho)
nuss = Topic.create!(
name: 'Nuss Bar',
topic_type: 'procedure'
).move_to_child_of(ortho)
## END PECTUS (xls 256) ##
## BEGIN SHALLOW ORTHOPEDIC (xls 258) ##
hip = Topic.create!(
name: 'hip',
topic_type: 'diagnosis'
).move_to_child_of(ortho)
Topic.create!(
name: 'protrusio acetabulae',
topic_type: 'diagnosis'
).move_to_child_of(hip)
Topic.create!(
name: 'hip replacement',
topic_type: 'procedure'
).move_to_child_of(hip)
foot = Topic.create!(
name: 'foot',
topic_type: 'diagnosis'
).move_to_child_of(ortho)
pes_planus = Topic.create!(
name: 'pes planus',
topic_type: 'diagnosis'
).move_to_child_of(foot)
Topic.create!(
name: 'orthotics',
topic_type: 'medication'
).move_to_child_of(pes_planus)
hind_foot = Topic.create!(
name: 'hind foot deformity',
topic_type: 'diagnosis'
).move_to_child_of(foot)
Topic.create!(
name: 'fusion',
topic_type: 'procedure'
).move_to_child_of(hind_foot)
hammer_toes = Topic.create!(
name: 'hammer toes',
topic_type: 'diagnosis'
).move_to_child_of(foot)
Topic.create!(
name: 'release',
topic_type: 'procedure'
).move_to_child_of(hammer_toes)
## END SHALLOW ORTHOPEDIC (xls 263) ##
## BEGIN OSTEOPEROSIS (xls 265) ##
osteoporosis = Topic.create!(
name: 'osteoporosis',
topic_type: 'diagnosis'
).move_to_child_of(ortho)
Topic.create!(
name: 'bone mineral density',
topic_type: 'measurement',
units_of_measurement: %w[Z-Score T-Score]
).move_to_child_of(osteoporosis)
Topic.create!(
name: 'compression fractures',
topic_type: 'diagnosis'
).move_to_child_of(osteoporosis)
Topic.create!(
name: 'hip fractures',
topic_type: 'diagnosis'
).move_to_child_of(osteoporosis)
Topic.create!(
name: 'wrist fractures',
topic_type: 'diagnosis'
).move_to_child_of(osteoporosis)
osteo_treatment = Topic.create!(
name: 'treatment',
topic_type: 'medication'
).move_to_child_of(osteoporosis)
Topic.create!(
name: 'calcium',
topic_type: 'medication'
).move_to_child_of(osteo_treatment)
Topic.create!(
name: 'vitamin D',
topic_type: 'medication'
).move_to_child_of(osteo_treatment)
Topic.create!(
name: 'biophosphonates',
topic_type: 'medication'
).move_to_child_of(osteo_treatment)
Topic.create!(
name: 'calcitonin',
topic_type: 'medication'
).move_to_child_of(osteo_treatment)
Topic.create!(
name: 'estrogen/analogue',
topic_type: 'medication'
).move_to_child_of(osteo_treatment)
Topic.create!(
name: 'forteo',
topic_type: 'medication'
).move_to_child_of(osteo_treatment)
## END OSTEOPEROSIS (xls 274) ##
## BEGIN SYMPTOMS (xls 276) ##
ortho_symptoms = Topic.create!(
name: 'symptoms',
topic_type: 'diagnosis'
).move_to_child_of(ortho)
ortho_pain = Topic.create!(
name: 'pain',
topic_type: 'middle'
).move_to_child_of(ortho_symptoms)
Topic.create!(
name: 'upper back pain ',
topic_type: 'diagnosis',
descriptors: pain_descriptors
).move_to_child_of(ortho_pain)
Topic.create!(
name: 'lower back pain',
topic_type: 'diagnosis',
descriptors: pain_descriptors
).move_to_child_of(ortho_pain)
Topic.create!(
name: 'hip',
topic_type: 'diagnosis',
descriptors: ['osteoarthritis', 'deep socket', 'dysplasia']
).move_to_child_of(ortho_pain)
Topic.create!(
name: 'knee',
topic_type: 'diagnosis',
descriptors: ['osteoarthritis', 'patellar instability', 'dysplasia', 'subluxation']
).move_to_child_of(ortho_pain)
Topic.create!(
name: 'ankle',
topic_type: 'diagnosis',
descriptors: %w[osteoarthritis dislocation subluxation instability]
).move_to_child_of(ortho_pain)
Topic.create!(
name: 'foot',
topic_type: 'diagnosis',
descriptors: %w[osteoarthritis dislocation subluxation instability]
).move_to_child_of(ortho_pain)
Topic.create!(
name: 'sciataca',
topic_type: 'diagnosis'
).move_to_child_of(ortho_symptoms)
Topic.create!(
name: 'activity limitation',
topic_type: 'diagnosis'
).move_to_child_of(ortho_symptoms)
## END SYMPTOMS (xls 283) ##
## BEGIN OPHTHALMOLOGIC (xls 285) ##
ophthalmo = Topic.create!(
name: 'ophthalmologic',
topic_type: 'root category'
)
phak = Topic.create!(
name: 'phakectomy',
topic_type: 'procedure',
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
iol = Topic.create!(
name: 'IOL',
topic_type: 'procedure',
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
irido = Topic.create!(
name: 'iridodensis',
topic_type: 'measurement',
units_of_measurement: %w[mm],
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
myopia = Topic.create!(
name: 'myopia',
topic_type: 'measurement',
units_of_measurement: %w[diopters],
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
Topic.create!(
name: 'globe length',
topic_type: 'measurement',
units_of_measurement: %w[mm]
).move_to_child_of(myopia)
Topic.create!(
name: 'amblyopia',
topic_type: 'diagnosis',
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
ectopia_lentis = Topic.create!(
name: 'ectopia lentis',
topic_type: 'diagnosis',
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
cataract = Topic.create!(
name: 'cataract',
topic_type: 'diagnosis',
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
Topic.create!(
name: 'glaucoma',
topic_type: 'diagnosis',
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
Topic.create!(
name: 'retinal thinning/holes',
topic_type: 'diagnosis',
descriptors: %w[left right both]
).move_to_child_of(ophthalmo)
retinal_detachment = Topic.create!(
name: 'retinal detachment',
topic_type: 'diagnosis',
descriptors: %w[buckle laser]
).move_to_child_of(ophthalmo)
## END OPHTHALMOLOGIC (xls 297) ##
## BEGIN GYNECOLOGIC/UROLOGIC (xls 299) ##
gyno = Topic.create!(
name: 'gynecologic/urologic',
topic_type: 'root category'
)
Topic.create!(
name: 'pelvic floor weakness',
topic_type: 'diagnosis',
descriptors: ['Kegel exercises']
).move_to_child_of(gyno)
Topic.create!(
name: 'bladder prolapse',
topic_type: 'diagnosis'
).move_to_child_of(gyno)
Topic.create!(
name: 'uterine prolapse',
topic_type: 'diagnosis'
).move_to_child_of(gyno)
## END GYNECOLOGIC/UROLOGIC (xls 302) ##
## BEGIN OBSTETRIC (xls 304) ##
pregnancy = Topic.create!(
name: 'obstetric (pregnancy)',
topic_type: 'root category'
)
preg_method = Topic.create!(
name: 'method',
topic_type: 'procedure'
).move_to_child_of(pregnancy)
Topic.create!(
name: 'spontaneous',
topic_type: 'diagnosis'
).move_to_child_of(preg_method)
Topic.create!(
name: 'IVF',
topic_type: 'diagnosis'
).move_to_child_of(preg_method)
Topic.create!(
name: 'PGD',
topic_type: 'diagnosis'
).move_to_child_of(preg_method)
Topic.create!(
name: 'surrogate',
topic_type: 'diagnosis'
).move_to_child_of(preg_method)
preg_outcome = Topic.create!(
name: 'outcome',
topic_type: 'diagnosis'
).move_to_child_of(pregnancy)
Topic.create!(
name: 'term',
topic_type: 'diagnosis'
).move_to_child_of(preg_outcome)
Topic.create!(
name: 'premature',
topic_type: 'diagnosis'
).move_to_child_of(preg_outcome)
abortion = Topic.create!(
name: 'abortion',
topic_type: 'procedure'
).move_to_child_of(preg_outcome)
Topic.create!(
name: 'spontaneous',
topic_type: 'diagnosis'
).move_to_child_of(abortion)
Topic.create!(
name: 'therapeutic',
topic_type: 'diagnosis'
).move_to_child_of(abortion)
preg_delivery = Topic.create!(
name: 'delivery',
topic_type: 'procedure'
).move_to_child_of(pregnancy)
vaginal = Topic.create!(
name: 'vaginal',
topic_type: 'procedure'
).move_to_child_of(preg_delivery)
Topic.create!(
name: 'assisted',
topic_type: 'procedure'
).move_to_child_of(vaginal)
Topic.create!(
name: 'induced - Pitocin',
topic_type: 'procedure'
).move_to_child_of(vaginal)
Topic.create!(
name: 'Caesarean',
topic_type: 'procedure'
).move_to_child_of(preg_delivery)
preg_anesthesia = Topic.create!(
name: 'anesthesia',
topic_type: 'medication'
).move_to_child_of(pregnancy)
Topic.create!(
name: 'epidural',
topic_type: 'medication',
).move_to_child_of(preg_anesthesia)
Topic.create!(
name: 'general',
topic_type: 'medication',
).move_to_child_of(preg_anesthesia)
Topic.create!(
name: 'none',
topic_type: 'medication',
).move_to_child_of(preg_anesthesia)
preg_diagnosiss = Topic.create!(
name: 'diagnosis',
topic_type: 'medication'
).move_to_child_of(pregnancy)
Topic.create!(
name: 'uterine rupture',
topic_type: 'diagnosis',
).move_to_child_of(preg_diagnosiss)
Topic.create!(
name: 'bleeding',
topic_type: 'diagnosis',
).move_to_child_of(preg_diagnosiss)
Topic.create!(
name: 'laceration',
topic_type: 'diagnosis',
).move_to_child_of(preg_diagnosiss)
Topic.create!(
name: 'lactation',
topic_type: 'diagnosis'
).move_to_child_of(pregnancy)
## END OBSTETRIC (xls 304) ##
## BEGIN NEUROLOGIC MIGRAINES (xls 326) ##
neuro = Topic.create!(
name: 'neurologic',
topic_type: 'root category'
)
headache = Topic.create!(
name: 'headache',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
common_migraine = Topic.create!(
name: 'common migraine',
topic_type: 'diagnosis'
).move_to_child_of(headache)
classic_migraine = Topic.create!(
name: 'classic migraine',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
complex_migraine = Topic.create!(
name: 'complex migraine',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
## END NEUROLOGIC MIGRAINES (xls 329) ##
## BEGIN NEUROLOGIC LOW ICP (xls 330) ##
low_icp = Topic.create!(
name: 'low ICP',
topic_type: 'diagnosis'
).move_to_child_of(headache)
chiari = Topic.create!(
name: 'Chiari malformation',
topic_type: 'diagnosis'
).move_to_child_of(low_icp)
Topic.create!(
name: 'MRI for Chiari Malformation',
topic_type: 'measurement',
units_of_measurement: %w[I II III IV]
).move_to_child_of(neuro)
dural_ectasia = Topic.create!(
name: 'dural ectasia',
topic_type: 'diagnosis',
descriptors: %w[chronic acute]
).move_to_child_of(low_icp)
Topic.create!(
name: 'MRI for dural ectasia',
topic_type: 'measurement',
units_of_measurement: ['scalloping', 'dural sac ratio', 'nerve root sleeve diameter', 'sagittal dural sac width']
).move_to_child_of(neuro)
blood_patch = Topic.create!(
name: 'blood patch',
topic_type: 'procedure'
).move_to_child_of(dural_ectasia)
fibrin = Topic.create!(
name: 'fibrin glue',
topic_type: 'procedure'
).move_to_child_of(dural_ectasia)
## END NEUROLOGIC LOW ICP (xls 333) ##
## BEGIN NEUROLOGIC SHALLOW (xls 335) ##
Topic.create!(
name: 'peripheral neuropathy',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
Topic.create!(
name: 'intracranial aneurysm',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
Topic.create!(
name: 'carotid dissection',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
Topic.create!(
name: 'vertebral artery dissection',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
Topic.create!(
name: 'cervical vascular tortuosity',
topic_type: 'diagnosis'
).move_to_child_of(neuro)
## END NEUROLOGIC SHALLOW (xls 341) ##
## BEGIN GASTROINTESTINAL (xls 343) ##
gastrointestinal = Topic.create!(
name: 'gastrointestinal',
topic_type: 'root category'
)
Topic.create!(
name: 'ulcerative colitis',
topic_type: 'diagnosis'
).move_to_child_of(gastrointestinal)
Topic.create!(
name: 'eosinophilic esophagitis',
topic_type: 'diagnosis'
).move_to_child_of(gastrointestinal)
Topic.create!(
name: 'diaphragmattic hernia',
topic_type: 'diagnosis'
).move_to_child_of(gastrointestinal)
Topic.create!(
name: 'intestinal rupture',
topic_type: 'diagnosis'
).move_to_child_of(gastrointestinal)
## END GASTROINTESTINAL (xls 348) ##
## RELATED TOPICS
dural_ectasia.update(
related: [
blood_patch.id,
fibrin.id,
headache.id
]
)
dissection.update(related: [root_replacement.id])
classic_migraine.update(
related: [
triptans.id,
antiepileptics.id,
calcium_channel_blocker.id,
tricyclics.id
]
)
complex_migraine.update(
related: [
triptans.id,
antiepileptics.id,
calcium_channel_blocker.id,
tricyclics.id
]
)
common_migraine.update(
related: [
triptans.id,
antiepileptics.id,
calcium_channel_blocker.id,
tricyclics.id
]
)
cataract.update(
related: [
phak.id,
iol.id
]
)
ectopia_lentis.update(
related: [
phak.id,
iol.id,
irido.id
]
)
kypho.update(
related: [
fusion.id,
harr.id,
bracing.id,
physio.id
]
)
thoracic_kypho.update(
related: [
fusion.id,
harr.id,
bracing.id,
physio.id
]
)
pc_morph.update(
related: [
ravitch.id,
nuss.id
]
)
pe_morph.update(
related: [
ravitch.id,
nuss.id
]
)
ap_morph.update(
related: [
ravitch.id,
nuss.id
]
)
Topic.all.each do |topic|
parents = topic.ancestors.reject { |t| t.topic_type == 'root category' }.map(&:id)
aunts = topic.aunts.map(&:id)
fam = (parents + aunts).uniq
if topic.related
topic.related += fam
topic.related_will_change!
else
topic.update(related: fam)
end
end
puts "#{Topic.count} topics seeded."
|
require 'spec_helper'
describe Spree::LineItem do
let(:order) { create :order_with_line_items, line_items_count: 1 }
let(:line_item) { order.line_items.first }
context '#save' do
it 'should update inventory, totals, and tax' do
# Regression check for #1481
line_item.order.should_receive(:create_tax_charge!)
line_item.order.should_receive(:update!)
line_item.quantity = 2
line_item.save
end
end
context '#destroy' do
# Regression test for #1481
it "applies tax adjustments" do
line_item.order.should_receive(:create_tax_charge!)
line_item.destroy
end
it "fetches deleted products" do
line_item.product.destroy
expect(line_item.reload.product).to be_a Spree::Product
end
it "fetches deleted variants" do
line_item.variant.destroy
expect(line_item.reload.variant).to be_a Spree::Variant
end
end
# Test for #3391
context '#copy_price' do
it "copies over a variant's prices" do
line_item.price = nil
line_item.cost_price = nil
line_item.currency = nil
line_item.copy_price
variant = line_item.variant
line_item.price.should == variant.price
line_item.cost_price.should == variant.cost_price
line_item.currency.should == variant.currency
end
end
# Test for #3481
context '#copy_tax_category' do
it "copies over a variant's tax category" do
line_item.tax_category = nil
line_item.copy_tax_category
line_item.tax_category.should == line_item.variant.product.tax_category
end
end
describe '.currency' do
it 'returns the globally configured currency' do
line_item.currency == 'USD'
end
end
describe ".money" do
before do
line_item.price = 3.50
line_item.quantity = 2
end
it "returns a Spree::Money representing the total for this line item" do
line_item.money.to_s.should == "$7.00"
end
end
describe '.single_money' do
before { line_item.price = 3.50 }
it "returns a Spree::Money representing the price for one variant" do
line_item.single_money.to_s.should == "$3.50"
end
end
context "has inventory (completed order so items were already unstocked)" do
let(:order) { Spree::Order.create }
let(:variant) { create(:variant) }
context "nothing left on stock" do
before do
variant.stock_items.update_all count_on_hand: 5, backorderable: false
order.contents.add(variant, 5)
order.create_proposed_shipments
order.finalize!
end
it "allows to decrease item quantity" do
line_item = order.line_items.first
line_item.quantity -= 1
line_item.target_shipment = order.shipments.first
line_item.save
expect(line_item).to have(0).errors_on(:quantity)
end
it "doesnt allow to increase item quantity" do
line_item = order.line_items.first
line_item.quantity += 2
line_item.target_shipment = order.shipments.first
line_item.save
expect(line_item).to have(1).errors_on(:quantity)
end
end
context "2 items left on stock" do
before do
variant.stock_items.update_all count_on_hand: 7, backorderable: false
order.contents.add(variant, 5)
order.create_proposed_shipments
order.finalize!
end
it "allows to increase quantity up to stock availability" do
line_item = order.line_items.first
line_item.quantity += 2
line_item.target_shipment = order.shipments.first
line_item.save
expect(line_item).to have(0).errors_on(:quantity)
end
it "doesnt allow to increase quantity over stock availability" do
line_item = order.line_items.first
line_item.quantity += 3
line_item.target_shipment = order.shipments.first
line_item.save
expect(line_item).to have(1).errors_on(:quantity)
end
end
end
end
|
module Post::Operation
class Import < Trailblazer::Operation
step :import_csv!
def import_csv!(options, params:, **)
CSV.foreach(params[:file].path, headers: true) do |row|
post = Post.new
post.title = row[0]
post.description = row[1]
post.status = row[2]
post.create_user_id = options[:current_user]
post.updated_user_id = options[:current_user]
post.created_at = Time.now
post.updated_at = Time.now
post.save!
end
true
end
end
end |
=begin
Write a method last_modified(file) that takes a file name
and displays something like this:
file was last modified 125.873605469919 days ago.
=end
require 'Time'
SECONDS_IN_DAY=24*60*60
def last_modified(file)
mod_time = (Time.now - File.mtime(file))/SECONDS_IN_DAY
puts "#{file} was last modified %.3f days ago\n" % mod_time
end
last_modified("testgameboard.rb")
last_modified("show_days.rb") |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
path = File.join(Rails.root, "static/recipes")
files = []
puts "Opening #{path}..."
i = 1
Dir.foreach(path) do |file|
next unless file.include?(".json")
files << file
print "#{i}..."
i += 1
end
puts "\nFiles read"
files.sort!
puts "Files sorted"
files.each_with_index do |file, index|
puts "#{index + 1}. Parsing #{file}..."
json = JSON.parse(File.read(File.join(path, file)))
hits = json["hits"]
category = json["q"]
hits.each_with_index do |hit, index|
recipe_hash = {
name: hit["recipe"]["label"],
category: category,
url: hit["recipe"]["url"],
energy: hit.dig("recipe", "totalNutrients", "ENERC_KCAL", "quantity"),
carbs: hit.dig("recipe", "totalNutrients", "CHOCDF", "quantity"),
fat: hit.dig("recipe", "totalNutrients", "FAT", "quantity"),
protein: hit.dig("recipe", "totalNutrients", "PROCNT", "quantity"),
data: hit
}
recipe_created = Recipe.create(recipe_hash)
if recipe_created.save
puts "#{index + 1}. Recipe \"#{recipe_created.name}\" created"
else
puts "#{index + 1}. Recipe \"#{recipe_created.name}\" skipped"
end
end
end
|
require 'net/http'
require 'json'
# Translates a string between two languages
# using Google Translate's AJAX service.
class Translate
def initialize(from, to)
# Languages to translate
@from = URI::encode(from)
@to = URI::encode(to)
# Google Translate
@gServiceUrl = "https://ajax.googleapis.com/ajax/services/language/translate"
@ver = "1.0"
end
def makeUrl(text)
text = "q=#{text}"
pair = "langpair=#{@from}|#{@to}"
ver = "v=#{@ver}"
"#{@gServiceUrl}?#{ver}&#{text}&#{pair}"
end
def translate(text)
uri = URI::encode(makeUrl(text))
json = Net::HTTP.get_response(URI(uri)).body
json = JSON.parse(json)
if json['responseStatus'] != 200
raise "Details: #{json['responseDetails']}, Status: #{json['responseStatus']}"
end
json['responseData']['translatedText']
end
end
|
class CheckForWin
def checkForWin?(board,player)
return checkForVerticalWins?(board,player) || checkForDiagonalWins?(board,player) || checkForHorizontalWins?(board,player)
end
def checkForVerticalWins?(board,player)
return checkForVerticalWin1?(board,player) || checkForVerticalWin2?(board,player) || checkForVerticalWin3?(board,player)
end
def checkForHorizontalWins?(board,player)
return checkForHorizontalWin1?(board,player) || checkForHorizontalWin2?(board,player) || checkForHorizontalWin3?(board,player)
end
def checkForDiagonalWins?(board,player)
return checkForDiagonalWin1?(board,player) || checkForDiagonalWin2?(board,player)
end
def checkForVerticalWin1? board,player
return board[0]==board[3] && board[3]==board[6] && board[6]==player
end
def checkForVerticalWin2? board,player
return board[1]==board[4] && board[4]==board[7] && board[7]==player
end
def checkForVerticalWin3? board,player
return board[2]==board[5] && board[5]==board[8] && board[8]==player
end
def checkForHorizontalWin1? board,player
return (board[0]==board[1] && board[1]==board[2] && board[2]==player)
end
def checkForHorizontalWin2? board,player
return (board[3]==board[4] && board[4]==board[5] && board[5]==player)
end
def checkForHorizontalWin3? board,player
return (board[6]==board[7] && board[7]==board[8] && board[8]==player)
end
def checkForDiagonalWin1? board,player
return (board[0]==board[4] && board[4]==board[8] && board[8]==player)
end
def checkForDiagonalWin2? board,player
return (board[2]==board[4] && board[4]==board[6] && board[6]==player)
end
end |
# frozen_string_literal: true
require "rails_helper"
module Renalware
module Diaverum
module Incoming
describe "rake diaverum:ingest", type: :task do
include DiaverumHelpers
let(:patient) { create(:hd_patient, local_patient_id: "KCH123", nhs_number: "0123456789") }
around do |example|
using_a_tmp_diaverum_path { example.run }
end
it "preloads the Rails environment" do
expect(task.prerequisites).to include "environment"
end
it "runs gracefully with with no files found" do
expect { task.execute }.not_to raise_error
end
it "logs to stdout" do
expect {
task.execute
}.to output(/Ingesting Diaverum HD Sessions/).to_stdout_from_any_process
end
context "when there a patient XML file waiting in the incoming folder having 2 sessions" do
context "when the file is valid" do
it "imports all the sessions and moves/creates necessary files" do
create_hd_type_map
copy_example_xml_file_into_diaverum_in_folder
task.execute
expect(HD::TransmissionLog.count).to eq(3) # a top level log and one per session
expect(HD::TransmissionLog.pluck(:error_messages).flatten).to eq []
expect(patient.hd_sessions.count).to eq(2)
# Processed files are moved from incoming folder..
expect(Dir.glob(Paths.incoming.join("*.xml")).count).to eq(0)
# ..to the incoming archive
expect(Dir.glob(Paths.incoming_archive.join("*.xml")).count).to eq(1)
# ..and a summary file created - in this case ending in ok.txt as there are 0 errors
expect(Dir.glob(Paths.outgoing.join("*_ok.txt")).count).to eq(1)
end
end
context "when the file is NOT valid" do
it "imports any sessions it can and moves/creates necessary files" do
copy_example_xml_file_into_diaverum_in_folder
# now delete all dialysates so we'll get a missing dialysate error
HD::Dialysate.delete_all
task.execute
expect(HD::TransmissionLog.count).to eq(3) # a top level log and one per session
expect(HD::TransmissionLog.pluck(:error_messages).flatten.uniq)
.to eq ["Couldn't find Renalware::HD::Dialysate Fresenius A7"]
expect(patient.hd_sessions.count).to eq(0)
# Processed files are moved from in folder..
expect(Dir.glob(Paths.incoming.join("*.xml")).count).to eq(0)
# ..to the incoming archive
expect(Dir.glob(Paths.incoming_archive.join("*.xml")).count).to eq(1)
# ..and a summary file created - in this case ending in ok.txt as there are 0 errors
expect(Dir.glob(Paths.outgoing.join("*_ok.txt")).count).to eq(0)
expect(Dir.glob(Paths.outgoing.join("*_err.txt")).count).to eq(1)
err_file_content = Dir.glob(Paths.outgoing.join("*_err.txt"))
.map { |p| File.read(p) }.join("")
expect(err_file_content)
.to match(/Couldn't find Renalware::HD::Dialysate Fresenius A7/)
end
end
end
def copy_example_xml_file_into_diaverum_in_folder
File.write(
Paths.incoming.join("diaverum_example.xml"),
create_patient_xml_document.to_xml
)
end
end
end
end
end
|
class AddColumnsToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_column :users, :lastname, :string
add_reference :users, :organization, index: true, foreign_key: true
add_reference :users, :user_type, index: true, foreign_key: true
end
end
|
require 'spec_helper'
describe 'sections/_assignment_set' do
before do
stub_template 'sections/_assignment_table' => "foo"
end
it "renders a table containing a set of assignments" do
asst = mock('assignment') do
stub(:content).and_return "Assignment content"
end
sa = mock('section_assignment') do
stub(:name).and_return '21'
stub(:due_date).and_return Date.new(2012, 7, 20)
stub(:assignment).and_return asst
end
render partial: 'sections/assignment_set',
locals: {table_id: 'current', sas: [sa], message: "Message", title: 'Some assignments'}
expect(rendered).to have_selector('div.assignment-block') do |div|
expect(div).to contain('Some assignments')
end
end
end
|
class Permission < ActiveRecord::Base
belongs_to :project
belongs_to :person
validates :project, presence: true
validates :person, presence: true
validates_uniqueness_of :project_id, :scope => :person_id
validates_inclusion_of :write, in: [true, false]
end
|
require 'spec_helper'
RSpec.describe SemrushRuby do
it 'has a version number' do
expect(SemrushRuby::VERSION).not_to be nil
end
describe 'configuration' do
context 'defaults' do
let(:client) { SemrushRuby::Client.new }
it 'uses the default api url' do
expect(client.api_url).to eq('http://api.semrush.com/')
end
end
context 'as a client option' do
let(:client) { SemrushRuby::Client.new api_url: 'http://test.semrush.com/' }
it 'uses the passed in api url' do
expect(client.api_url).to eq('http://test.semrush.com/')
end
end
context 'as a module var' do
before do
SemrushRuby.configure do |sr|
sr.api_url = 'http://other.semrush.com/'
end
end
after do
SemrushRuby.reset_defaults!
end
let(:client) { SemrushRuby::Client.new }
it 'uses the default api url' do
expect(client.api_url).to eq('http://other.semrush.com/')
end
end
end
end
|
class ActSection < ActiveRecord::Base
belongs_to :act
belongs_to :act_part
def label
"Section #{section_number}: #{title}"
end
def legislation_uri_for_subsection subsection_number
"#{legislation_url}/#{subsection_number}"
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user){FactoryBot.create(:user)}
let(:friends){FactoryBot.create_list(:user,4)}
describe "friendships" do
it "can get a list of Users that are friends" do
user.friendships.create(friend: friends.first, status: :accepted)
friends[1..-1].each {|f| f.friendships.create(friend: user, status: :accepted)}
expect(user.friends).to match_array(friends)
end
it "can get a list of friend requests and the requesters" do
friend = friends.first
user.requesters << friend
expect(user.friend_requests.where(friend: friend).length).to be 1
expect(user.friend_requests.where(friend: friend).first.friend).to eq friend
end
context "when accepting a friend request" do
let(:user){FactoryBot.create(:user)}
let(:friend){FactoryBot.create(:user)}
before do
user.requesters << friend
user.friend_requests.where(friend: friend).first.accepted!
end
it "updates user.friends with the friend that sent the request" do
expect(user.friends).to include(friend)
end
it "updates friend.friends with the friend that sent the request" do
expect(friend.friends).to include(user)
end
it "deletes the request" do
expect(user.friend_requests.where(friend: friend).empty?).to be true
end
end
end
describe "posts" do
before {friends.each{|f| f.friendships.create(friend: user, status: :accepted)}}
it "can create a post" do
content = "Test post"
user.posts.create(content: content)
expect(user.posts.first.content).to eq content
end
it "can get a list of friend's posts" do
posts = []
content = "Test post"
friends.each {|f| 2.times{posts << f.posts.create(content: content)}}
expect(user.friends).to match_array(friends)
expect(user.friends_posts).to match_array(posts)
end
it "can get a list of friend's unseen posts" do
unseen_posts = []
content = "Test post"
friends.each {|f| 2.times{ f.posts.create(content: content)}}
friends.each {|f| f.posts.first.viewers << user}
friends.each {|f| unseen_posts << f.posts.second }
expect(user.unseen_posts).to match_array(unseen_posts)
end
end
end
|
class VolunteerOpportunity
include MongoMapper::Document
attr_accessor :search_relevance, :rank, :current_page, :total_pages
USELESS_TERMS = ["a", "the", "of", "it", "for", "is", "i", "to", "in", "be", "and", "on"]
PUNCTUATION = Regexp.new("[>@!*~`;:<?,./;'\"\\)(*&^{}#]")
key :title, String
key :description, String
key :hours_requested, String
key :number_requested, String
key :requirements, String
key :population_served, String
key :tags, Array, :default => []
key :contact_name, String
key :contact_email, String
key :contact_phone, String
key :status, String, :default => "active"
key :search_terms, Array, :default => []
key :parent_volunteer_opportunity
timestamps!
belongs_to :service
validates_presence_of :title, :description
before_save :create_search_terms
scope :pending, lambda { where(:status => "pending") }
scope :updated, lambda { where(:status => "updated") }
scope :search, lambda { |term| where(:status => "active", :search_terms => cleaned_search_terms(term)) }
scope :active, lambda { where(:status => "active") }
def self.cleaned_search_terms(search_term)
unless search_term.nil?
return search_term.gsub(/\//, " ").gsub(PUNCTUATION, " ").downcase.split.uniq
end
end
def create_search_terms
self.search_terms = [contact_email, contact_name].delete_if(&:nil?).map(&:downcase)
[title, description, requirements, tags, population_served].each do |term|
next if term.nil?
term = term.join(" ") if term.is_a? Array
self.search_terms += term.gsub(/\//, " ").gsub(PUNCTUATION, "").downcase.split.uniq
end
self.search_terms.delete_if {|term| USELESS_TERMS.include? term}
self.search_terms.delete_if(&:nil?)
self.search_terms.delete_if(&:empty?)
self.search_terms.uniq!
#self.name_parts = title.gsub(/\//, " ").gsub(PUNCTUATION, "").downcase.split.uniq
#self.name_parts.delete_if {|term| USELESS_TERMS.include? term}
end
def rank_search(search_term)
@rank = 0
search_array = search_term.gsub(PUNCTUATION, "").downcase.split.uniq
search_rank_array = search_array & search_terms.uniq
@rank = search_rank_array.length
if title =~ %r[#{search_term.strip}]i
@rank = @rank * 3
end
if description =~ %r[#{search_term.strip}]i
@rank = @rank * 3
end
@rank
end
end
|
# == Schema Information
#
# Table name: courses
#
# id :integer not null, primary key
# name :string
# content :text
# video_id :string
# track_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# position :integer
#
# Indexes
#
# index_courses_on_track_id (track_id)
#
class Course < ActiveRecord::Base
belongs_to :track
acts_as_list scope: :track
validates :name, presence: true
validates :video_id, presence: true
end
|
class FixDataType < ActiveRecord::Migration[5.1]
def change
rename_column :build_sessions, :user_ids, :user_id
end
end
|
class AddCastleTrackingToGames < ActiveRecord::Migration[5.0]
def change
add_column :games, :white_can_castle_king_side, :boolean, default: true
add_column :games, :black_can_castle_king_side, :boolean, default: true
add_column :games, :white_can_castle_queen_side, :boolean, default: true
add_column :games, :black_can_castle_queen_side, :boolean, default: true
end
end
|
require 'spec_helper'
Run.all(:read_only) do
use_pacer_graphml_data(:read_only)
describe '#as_var' do
it 'should set the variable to the correct node' do
vars = Set[]
route = graph.v.as_var(:a_vertex)
route.in_e(:wrote) { |edge| vars << route.vars[:a_vertex] }.count
vars.should == Set[*graph.e.e(:wrote).in_v]
end
it 'should not break path generation (simple)' do
who = nil
r1 = graph.v.as_var(:who)
r = r1.in_e(:wrote).out_v.v { |v|
who = r1.vars[:who]
}.paths
r.each do |path|
path.to_a[0].should == who
path.length.should == 3
end
end
it 'should not break path generation' do
who_wrote_what = nil
r1 = graph.v.as_var(:who)
r = r1.in_e(:wrote).as_var(:wrote).out_v.as_var(:what).v { |v|
who_wrote_what = [r1.vars[:who], r1.vars[:wrote], r1.vars[:what]]
}.paths
r.each do |path|
path.to_a.should == who_wrote_what
end
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :setup_user
# make current user available in all view templates
helper_method :current_user
#memoization
def current_user
@current_user ||= User.where(id: session[:user_id]).first
end
def setup_user
@user = User.new
end
end
|
class DealerBuilder
attr_reader :computer
def initialize
@dealer = Dealer.new
@dealer.contact_info = ContactInfo.new
end
def columns_values
columns = Dealer.column_names + ContactInfo.column_names
columns -= %w[created_at updated_at]
columns
end
def contact_info
@dealer.contanct_info = ContactInfo.new
end
def name=(name)
@dealer.name = name
end
def category=(category)
@dealer.category = category
end
def sf_id=(sf_id)
@dealer.sf_id = sf_id
end
def longitude=(longitude)
@dealer.longitude = longitude
end
def latitude=(latitude)
@dealer.latitude = latitude
end
def street=(street)
@dealer.contact_info.street = street
end
def city=(city)
@dealer.contact_info.city = city
end
def zip=(zip)
@dealer.contact_info.zip = zip
end
def country=(country)
@dealer.contact_info.zip = country
end
def state=(state)
@dealer.contact_info.state = state
end
def phone=(phone)
@dealer.contact_info.phone = phone
end
def dealer
obj = @dealer.dup
@dealer = Dealer.new
@dealer.contact_info = ContactInfo.new
obj
end
end
|
class OpenMat < ActiveRecord::Base
belongs_to :user
validates :street_address, :city, :state, :starts_at, :asset, presence: true
has_attached_file :asset, styles: {
large: '400x400>',
medium: '300x300>',
small: '140x140',
thumb: '64x64!'
}
validates_attachment_content_type :asset, content_type: /\Aimage\/.*\Z/
has_many :registrations, dependent: :destroy
def expired?
starts_at < Time.now
end
def self.upcoming
where("starts_at >= ?", Time.now).order("starts_at")
end
end |
require 'rails_helper'
RSpec.describe "stores/edit", type: :view do
before(:each) do
@store = assign(:store, Store.create!(
:name => "MyString",
:email => "MyString",
:open => false,
:image => "MyString",
:photos => "",
:tags => "",
:description => "MyString",
:lat => "",
:long => "",
:votes => "",
:props => ""
))
end
it "renders the edit store form" do
render
assert_select "form[action=?][method=?]", store_path(@store), "post" do
assert_select "input#store_name[name=?]", "store[name]"
assert_select "input#store_email[name=?]", "store[email]"
assert_select "input#store_open[name=?]", "store[open]"
assert_select "input#store_image[name=?]", "store[image]"
assert_select "input#store_photos[name=?]", "store[photos]"
assert_select "input#store_tags[name=?]", "store[tags]"
assert_select "input#store_description[name=?]", "store[description]"
assert_select "input#store_lat[name=?]", "store[lat]"
assert_select "input#store_long[name=?]", "store[long]"
assert_select "input#store_votes[name=?]", "store[votes]"
assert_select "input#store_props[name=?]", "store[props]"
end
end
end
|
#
# Cookbook:: thing.resource_test
# Resource:: thing
#
resource_name :thing
provides :thing
property :thing_name, [String], required: true
property :registry, [String], required: true
action :create do
if registry_key_exists?(new_resource.registry)
Chef::Log.info('thing:create, the hive exists')
else
Chef::Log.info('thing:create, the hive DOES NOT exists')
end
my_thing = ResourceTest::Helpers::Thing.new(new_resource.thing_name, new_resource.registry)
my_thing.do(new_resource.thing_name, new_resource.registry)
end
action_class do
include ResourceTest::Helpers
end
|
require 'use_cases/bikes/find_bike'
module Api
module V1
class BikesController < ApplicationController
def show
find_bike_use_case = UseCases::Bikes::FindBike.new
find_bike_use_case.on(:find_bike_success) { |bike| render json: bike, status: :ok }
find_bike_use_case.on(:find_bike_fail) { head :not_found }
find_bike_use_case.call(bike_id)
end
private
def permitted_params
params.permit(
:bike_id,
:staion_id,
:user_id
)
end
def bike_id
permitted_params[:bike_id]
end
end
end
end
|
module Countable
def items_by_merch_count
merch_items_hash.values.map do |item_array|
item_array.length
end
end
def invoices_by_merch_count
count = merch_invoices_hash.values.map do |invoice_array|
invoice_array.length
end
count
end
def top_days_by_invoice_count
days_high_count = days_invoices_hash.select do |days, invoices|
invoices > (average_invoices_per_day + avg_inv_per_day_std_dev)
end
days_high_count.keys
end
end
|
json.array!(@github_issues) do |github_issue|
json.extract! github_issue, :id, :github_id, :path
json.url github_issue_url(github_issue, format: :json)
end
|
namespace :sinatrabar do
desc "Sets up configuration and database"
task :install do
# Install task (sets up config/pianobar) and then runs db:migrate
end
desc "Starts the application"
task :start do
# Starts application
end
end
namespace :db do
desc "Set up initial database"
task :setup do
# migration task
end
desc "Drops application database"
task :drop do
# drop task
end
end
|
# To run this code, be sure your current working directory
# is the same as where this file is located.
# ruby 6.rb
# EXERCISE
# Write a method called shuffled_deck that returns an array that
# represents a shuffled deck of cards.
# Write a method called deal_hand that allows an argument specifying
# the number of cards to be dealt. For example, deal_hand(5) should
# return an array of 5 random cards.
# HINTS
# http://ruby-doc.org/core-2.5.1/Array.html
# Some methods of interest ;)
# - shuffle
# - product
# - slice
def shuffled_deck
ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"]
suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
brand_new_deck = ranks.product(suits)
deck_that_is_shuffled = brand_new_deck.shuffle
deck_that_is_shuffled
end
def deal_hand(number_of_cards)
shuffled_deck.slice(0, number_of_cards)
end
# Write out shuffled_deck, just so you can see what it looks like.
# puts shuffled_deck.inspect
puts deal_hand(2).inspect |
class ApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :set_locale
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :role, :phone])
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :role, :phone])
end
def set_locale
I18n.locale = current_user.try(:locale) || I18n.default_locale
end
end
|
class ChangeColumnName < ActiveRecord::Migration[5.2]
def change
rename_column :bookings, :dote, :date
end
end
|
class CreateEngineerRegistrationTypes < ActiveRecord::Migration[5.2]
def change
create_table :engineer_registration_types, comment: EngineerRegistrationType.model_name.human do |t|
t.string :name, comment:'流入種別'
t.string :description, comment: '流入種別詳細'
t.integer :sort, comment:'並び順'
t.timestamps
end
end
end
|
class RatingsController < ApplicationController
def index
@ratings = Rating.all
end
def show
@rating = Rating.find(params[:id])
end
def new
@rating = Rating.new
end
def edit
@rating = Rating.find(params[:id])
end
def create
sessionUser = UsersController.getSessionUser(session)
@snippet = Snippet.find(params[:snippet_id])
#@rating = Rating.take({:snippet_id => @snippet.id, :user_id => sessionUser.id }) rescue nil
@rating = Rating.where({:snippet_id => @snippet.id, :user_id => sessionUser.id }).take
puts "Snippet:"
puts @snippet.inspect
puts "Rating:"
puts @rating.inspect
puts "User ID:"
puts sessionUser.id
puts "!!!!!!!!!!!!!!!!!!!!!!!!!!"
dataHash = rating_params.merge({:user_id => sessionUser.id})
sucess = false
if @rating
if @rating.update(dataHash)
success = true
end
else
@rating = @snippet.ratings.create(dataHash)
if @rating.save
success = true
end
end
if success
redirect_to @rating
else
render 'new'
end
end
def update
@rating = Rating.find(params[:id])
if @rating.update(rating_params)
redirect_to @rating
else
render 'edit'
end
end
def destroy
@rating = Rating.find(params[:id])
@rating.destroy
redirect_to ratings_path
end
private
def rating_params
params.require(:rating).permit(:rating_mark_id, :snippet_id)
end
end
|
require 'fastlane_core/ui/ui'
module Fastlane
UI = FastlaneCore::UI unless Fastlane.const_defined?("UI")
module Helper
class Ipa
ATTRS = [:size, :format_size]
attr_accessor(*ATTRS)
def initialize(ipa_path)
return nil unless ipa_path
return nil if ipa_path.empty?
return nil unless File.exist?(ipa_path)
# size
@size = FileHelper.file_size(ipa_path)
@format_size = FileHelper.format_size(@size)
end
def to_hash
{
size: @size,
format_size: @format_size
}
end
def generate_json
return @result_json if @result_json
@result_json = JSON.generate(generate_hash)
@result_json
end
def generate_hash
return @result_hash if @result_hash
@result_hash = to_hash
@result_hash
end
end
end
end
|
class Api < Grape::API
format :json
prefix :api
get :ping do
{ :pong => 'ok' }
end
end
|
class AddGaAccountNameAndGaWebsiteToAdvertisers < ActiveRecord::Migration
def change
remove_column :advertisers, :ga_script
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.