text
stringlengths
10
2.61M
# 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) Book.create(title: "No Hero", author: "Yuwo", price: 2000, genre: 1, released_at: "2018/9/10", story: "Xiang Ye (Ah Ye) and Charles have the fated arrangement of master and servant. In the depths of darkness, Ah Ye scooped up Charles – a vampire butler. Possessing a fervid passion for service, Charles single-mindedly attends to the secretive young master Ah Ye – regardless of his ferocious appetite, abhorrent taste in clothing, and relationship failings – for the master is always right.On the other hand, in the chaotic era of scientifically enhanced humans, powerful heroes become the protectors of normal citizens, going where evil needs subduing. This young master may be secretive, but he is our hero.") Book.create(title: "Unique Legend", author: "Hong Lin", price: 1000, genre: 1, released_at: "2019/11/7", story: "Chu Ming Yang is an extremely unfortunate high school student who accidentally enrolls into an academy of a dubious nature, where it is the norm to jump in front of moving trains, get dismembered during orientation, and crushed by vindictive bouncing classrooms. Can he stay alive or will he die from the rigors of school? Why have evil spirits suddenly acquired a taste for his flesh?") Book.create(title: "Residence of Monsters", author: "Lan Qi Zuo Jun", price: 3000, genre: 2, released_at: "2019/11/8", story: "With the start of a boarding school life, and as a first-year student, he unluckily falls into a situation of having no living quarters to stay in. Accidentally stumbling across the legendary ‘haunted house’, and furthermore inadvertently releasing a forbidden seal– “Human! You actually dared to trespass…” “I’m really sorry! Are you the owner? Can I pay the lodging fee?” “……Haven’t you realized the difference of us from normal humans?” “Uh, you all look exceptionally handsome?” (⊙∀⊙)ノ “……╬” For a (beep–) goal, the demons decide to pretend to be students and sneak into the school. Due to a (beep–) reason, the boy is forced to live in the residence for a certain amount of time. The demons who do not know the affairs of life meet a zealous and simple boy and accept the overly chaotic affairs of the school + living together, which is where the story ardently begins!") Book.create(title: "The Legend of Sun Knight", author: "Yuwo", price: 5115, genre: 2, released_at: "2016/9/6", story: "I am a knight. To be precise, I am the Church of the God of Light’s Sun Knight. The Church of the God of Light worships and serves the God of Light, and theirs’ is one of the three largest religions on this continent. As the whole continent knows, the Church of the God of Light has the Twelve Holy Knights, and each one has his own unique personality and features. To be the Sun Knight is to have shining golden hair, sky blue eyes, a compassionate nature, and a brilliant smile. “The benevolent God of Light will forgive your sins.” I must have said that line at least a million times in my time as the Sun Knight. However, the greatest wish in my life is to be able to stand before the entire continent and roar, “Damn your ‘the whole continent knows’! This Sun Knight just doesn’t feel like smiling! I just don’t want to forgive these human tr*shes! I just want to pepper my sentences with ‘f***’!” Unfortunately, even to this day, I continue to wear a smile as I say, The benevolent God of Light will forgive your sins.") Book.create(title: "Nightfall", author: "Mao Ni", price: 3345, genre: 3, released_at: "2017/9/8", story: "Chang An, capital of Tang, the most powerful empire in the continent. A heaven wrecking massacre shook the city to its core. Amidst the incident, a young boy named Ning Que managed to get away, dug out from a pile of corpses along with a little girl called Sang Sang. Years passed, and since that day the two of them lived together. Together with Sang Sang they both entered the military, with plausible military achievements, they were recommended into the Scholar School, which began their miraculous journey.") Book.create(title: "The Girl Who Ate a Death God", author: "Chomoran", price: 3116, genre: 4, released_at: "2018/4/18", story: "What happens when one eats Death? Personally, I don’t really know. What I do know is merely one thing. I’m hungry. Therefore, I’ll take the heads of these guys and deliver them to my superiors. Surely, I’ll be able to eat delicious food. Come, if preparations are in order, we depart.") Book.create(title: "Super Dimensional Wizard", author: "Shepherd Fox", price: 4113, genre: 5, released_at: "2016/7/11", story: "The status of a wizard is transcendent in all continents and in the universal plane. Mysterious, wise, cruel and bloodthirsty are synonymous with wizards. But what does a real wizard look like? After coming into contact with the world of wizards, Angel came to the conclusion: Wizards are a group of people who illuminate themselves with intellect-driven ideas, but are in a dialectical world with a materialistic attitude. In other words, this is a group of alternative scientists who walk alone in a rigorous manner in the pursuit of understanding reality.") Book.create(title: "Kenkyo, Kenjitsu o Motto ni Ikite Orimasu", author: "Hiyoko no keiki", price: 3116, genre: 6, released_at: "2015/9/30", story: "It was something that happened while I was waiting for the day of the primary school entrance exam. I realised that I had become one of the characters of a shoujo manga that I loved reading in my old life, ‘you are my dolce’. The role I was assigned was a character who bullied the commoner protagonist and tried to get in the way of her love with a rich boy nicknamed Emperor; a typical villainess rich girl, Kisshouin Reika. At the end of the story, Reika suffered the Emperor’s retribution and even her family fell into ruin. With the villain gone, the protagonist and the Emperor overcame their trials and became a couple. And they lived happily ever after. Wait, that’s terrible for meee! The manga ended there, but I have to continue living my life after my family is ruined! The protagonist can enjoy her romance or love or whatever on her own. I’ll erase my presence so that I don’t anger the Emperor. Eh-? The story isn’t progressing well because there’s no villain, you say? But I’m busy saving up money and studying so that I can live well after the collapse.") Book.create(title: "Common Sense of a Duke’s Daughter", author: "Reia", price: 5228, genre: 7, released_at: "2019/4/29", story: "When a young woman is killed in a traffic accident on her way home from work at a tax bureau, she suddenly finds herself transported to the world of the otome game she was playing the night before – but instead of the heroine, she’s been reincarnated as the bad guy! Using her knowledge of the game, “Iris” manages to avert personal disaster and decides to rebuild her life with her modern-day economic know-how. This is one mean girl who isn’t going to let her perceived reputation stop her from being a heroine!") Book.create(title: "Trash of the Count’s Family", author: "Yoo Ryeo Han", price: 4482, genre: 8, released_at: "2020/5/11", story: "When I opened my eyes, I was inside a novel. [The Birth of a Hero]. [The Birth of a Hero] was a novel focused on the adventures of the main character, Choi Han, a high school boy who was transported to a different dimension from Earth, along with the birth of the numerous heroes of the continent. I became a part of that novel as the tr*sh of the Count’s family, the family that oversaw the territory where the first village that Choi Han visits is located. The problem is that Choi Han becomes twisted after that village, and everyone in it, are destroyed by assassins. The bigger problem is the fact that this s*upid tr*sh who I’ve become doesn’t know about what happened in the village and messes with Choi Han, only to get beaten to a pulp. “…This is going to be a problem.” I feel like something serious has happened to me. But it was worth trying to make this my new life.") Book.create(title: "How to Live as the Enemy Prince", author: "Cha Seo Hyeon", price: 5933, genre: 9, released_at: "2020/7/26", story: "After his death, Bern awakens 10 years into the past as the third prince of Kailis, the enemy country. He became a weak and incompetent prince who was to be assassinated before turning 15-years-old.") Book.create(title: "The Editor Is the Novel’s Extra", author: "Jongsuil", price: 3114, genre: 10, released_at: "2020/3/15", story: "Kim Jeongjin, an editor of a publishing company on the brink of closing due to bankruptcy, ends up transmigrating inside a fantasy novel as the incompetent youngest son of a wealthy family. And here he thought that he should live a rich life in this life… Why was I given a high-level skill? Don’t even bother!") Book.create(title: "Omniscient Reader’s Viewpoint", author: "Sing-Shong", price: 2526, genre: 11, released_at: "2018/2/8", story: "Only I know the end of this world. One day our MC finds himself stuck in the world of his favorite webnovel. What does he do to survive? It is a world struck by catastrophe and danger all around. His edge? He knows the plot of the story to end. Because he was the sole reader that stuck with it. Read his story to see how he survives!") Book.create(title: "Stellar Transformation", author: "I Eat Tomatoes", price: 4181, genre: 12, released_at: "2016/5/16", story: "In a galaxy far away, there is a kid without innate ability to practice internal techniques. So, in order to gain the respect of his father, he resolutely chooses to follow the more difficult and painful path of practicing external techniques. As the years go by, he grows up, but what really changes his life is a mysterious meteoric crystal stone – the Meteoric Tear. This stone fuses with the young man’s body unnoticed, and he seems to undergo drastic transformations as a result. After that, everything is changed. Eventually his father knows that the son for whom he hasn’t really shown a lot of consideration possesses astonishing abilities. And there’s a lot more to come.") Book.create(title: "The Desolate Era", author: "I Eat Tomatoes", price: 4517, genre: 13, released_at: "2018/4/12", story: "Fate had never been kind to Ji Ning. Wracked by illnesses and infirm his entire life on Earth, Ji Ning knew early on that he would die as a teenager. What he didn’t know was that there really was such a thing as life after death and that the multiverse was a far larger place than he thought. A lucky twist of fate meant that Ji Ning was reborn into a world of Immortals and monsters, of Ki Refiners and powerful Fiendgods, a world where Dynasties lasted for millions of years. A world which is both greater… and yet also smaller… than he ever could imagine. He would have the opportunity to join them, and in this life, Ji Ning swore to himself, he would never let himself be weak again! The Era he was born into was a Desolate one, but Ji Ning would make it his era.") Book.create(title: "Swallowed Star", author: "Wo Chi Xi Hong Shi", price: 5310, genre: 4, released_at: "2020/7/19", story: "Year 2056, in a city in the Yuan Jiang Su Jin area. On top of a ruined, shattered six story residential apartment sits a teenager wearing a combat vest, militaristic trousers, and alloyed battle boots. On his back is a hexagonal shield and equipped is a blood-shadow battle knife. He sits there silently on the edge of the roof. At this time, the sparkling sky was shining and there was a refreshing breath within the air that blew towards him. However, there was only silence within the ruined, deserted city, with an occasional howl that makes your heart skip a beat.") Book.create(title: "The Villain is Being Suspiciously Kind", author: "Doreda", price: 3938, genre: 5, released_at: "2019/4/9", story: "In this story the heroine, Citrina is a transmigrator. In the original story, the female protagonist’s sister, Citrina, worked hard like a dog for her family only to be killed by the villain. So she decided to change the original plot, in the direction where she will befriend the villain and prevent him from blackening. “Citrina, I will do everything you need to do.” Good. After many failures, she was able to be acquainted with the villain. Everything’s perfectly great. I think I already saved my life, so it’s time to leave and make money, and come back as a successful person. “Don’t be nice… only to me.” “I’m not nice to anyone else. ” The villain in the novel smiled tenderly. “I’ll only be nice to you.” Him being kind and friendly is a little suspicious. “Don’t ask anyone else. Use me instead.” “I… you?” ‘Use you?’ Citrina looked at him. Then, his lips formed in a single line. As he looked at her, Desian whispered, as if repeating to her. “Use me however you want.” With that, he reached out. He slowly tucked the hair that flowed down, in Citrina’s ears. His hands added color to her hair. The hand that touched her was a little cold, it gave her chills. “In fact…” A soft whisper came out from Desian’s lips. Don’t use anyone but me.") Book.create(title: "Time Limit", author: "Essie", price: 6144, genre: 6, released_at: "2020/7/7", story: "Lady Lariette is diagnosed with a disease which gives her a three-month deadline. “Since I am going to die, I might as well go crazy!” It started with screwing her fiancé and having a relationship with the monster duke. But she didn’t realize it until it was too late. There was no time limit and it was a misdiagnosis! Mr. Asrazan smiled brightly, If you try to run away now, you will face consequences.") Book.create(title: "The Lady Wants To Rest", author: "Pig Cake", price: 4443, genre: 7, released_at: "2020/10/11", story: "In the distant past, I was cursed by my dealings with the world. Over the next 1,000 years, I lived an endless life. There isn’t a single life I haven’t experienced. I have been the most noble and humble person in the world, I have become a beggar, I have been revered as a saint, and I have been burned as a witch. And after my most miserable and painful life, I thought of it all again. ‘It’s all bothering me now—I’d like to take a break, please. I’ve decided to live a life of a lazy sloth this time, but why are people still bothering me? Let me get some rest.’ Her story of wanting to rest!") Book.create(title: "It Seems Like I Got Reincarnated Into The World of a Yandere Otome Game", author: "Hanaki Momiji", price: 5310, genre: 8, released_at: "2019/3/27", story: "As a precocious child, Lycoris suffers from a strange sense of deja vu. On the day her father told her about her fiancé, she realizes that her fiancé was a character from an otome game she once played in a previous life. “I am the heroine’s rival from the game? And in the bad ending, I get stabbed to death? What a joke.” A story in which the protagonist is determined to avoid a yandere situation.") seed_users = ['Reika', 'Kuro', 'Momiji', 'Usagi', 'Misaki', 'Edward', 'Christine', 'Crystal', 'Sherlock', 'Totoro', 'Yushin', 'Charlie', 'Anastasia', 'Khun', 'Angel'] n = 0 seed_users.each do |seed_user| n = n + 1 user = User.new( name: "#{seed_user}", email: "user#{n}@example.com", password: "password_for_user#{n}", introduce: "Hello! I am #{seed_user}.", admin: false, icon: open("#{Rails.root}/db/seed_fixtures/#{seed_user}.jpg"), ) user.save end admin_user = User.new( name: "admin", email: "admin@example.com", password: "password_for_admin", introduce: "Thank you for watching my app!", admin: true, icon: open("#{Rails.root}/db/seed_fixtures/admin.jpg"), ) admin_user.save 10.times do |b| 5.times do |u| u = u + 1 Review.create( speciality: rand(0..25), knowledge: rand(0..25), story: rand(0..25), like: rand(0..25), summary: "Review summary", body: "I am sure. You will like it.", book_id: rand(1..30), user_id: u, ) Comment.create( body: "Give it a try", book_id: rand(1..30), user_id: u, ) Favorite.create( book_id: rand(1..30), user_id: u, ) end end 3.times do |b| b = b + 1 10.times do |u| u = u + 1 Relationship.create( follower_id: u, followed_id: b+u, ) end end 5.times do |b| b = b + 1 Review.create( speciality: 25, knowledge: 25, story: 25, like: 25, summary: "Review summary", body: "I am sure. You will like it.", book_id: b+10, user_id: 17 ) Comment.create( body: "Give it a try", book_id: b, user_id: 17, ) Favorite.create( book_id: b, user_id: 17, ) Relationship.create( follower_id: 17, followed_id: b+5, ) end
module Golds module Employees class CompanyCost < Struct.new(:gross_salary) def yearly_salary gross_salary.yearly end def yearly_social_security gross_salary.yearly * 0.2375 end def yearly_food_allowance 4.52 * 21 * 11 end def yearly_health_insurance gross_salary.yearly * 0.01 end def yearly_total ( yearly_salary + yearly_social_security + yearly_food_allowance + yearly_health_insurance ) end end end end
require 'rails_helper' RSpec.describe Merchant, type: :model do context "relationships" do it { should have_many(:invoices) } it { should have_many(:items) } end it "returns revenue for a merchant" do customer = create(:customer) merchant = create(:merchant, name: 'Billy Bob Bacon') invoice = create(:invoice, merchant: merchant, customer: customer) items = create_list(:item, 2, merchant: merchant) InvoiceItem.create(invoice: invoice, item: items.first, unit_price: 1000, quantity: 2) InvoiceItem.create(invoice: invoice, item: items.second, unit_price: 2500, quantity: 3) create(:transaction, invoice: invoice) expect(Merchant.find(merchant.id).revenue).to eq("95.0") end it "returns revenue for a merchant" do customer = create(:customer) merchant = create(:merchant, name: 'Billy Bob Bacon') invoice = create(:invoice, merchant: merchant, customer: customer) items = create_list(:item, 2, merchant: merchant) InvoiceItem.create(invoice: invoice, item: items.first, unit_price: 1000, quantity: 2) InvoiceItem.create(invoice: invoice, item: items.second, unit_price: 2500, quantity: 3) create(:transaction, invoice: invoice) expect(Merchant.find(merchant.id).revenue).to eq("95.0") end end
module Abstraxion class Cursor < GameObject def initialize(options = {}) super(options.merge(:image => Image["cursor.png"])) self.zorder = ZOrder::Cursor end def update @x = $window.mouse_x + 6 @y = $window.mouse_y + 10 end end end
class RefundRedWorker include Sidekiq::Worker def perform(red_bag_id) red_bag = RedBag.find_by(id: red_bag_id) return unless red_bag return unless red_bag.state.normal? # if (Time.now - red_bag.created_at) / 1.hour >= 24 if (Time.now - red_bag.created_at) / 1.minutes >= 2 redis_key = RedBag.build_redis_key(red_bag_id) lock = Redis::Lock.new("#{redis_key}:lock") lock.lock do bag_val = Redis::Value.new("#{redis_key}:value", marshal: true) if bag_val.value bag_val.value = bag_val.value.merge({ refunded: true }) end red_hash = Redis::HashKey.new("#{redis_key}:hash_key") total_win = red_hash.all.map { |k, v| v }.inject(0) { |sum, n| sum + BigDecimal.new(n) } db_win = red_bag.red_bag_items.sum(:money) win = total_win >= db_win ? total_win : db_win red_bag.state = 'refunded' red_bag.balance = red_bag.money - win if RefundToCardService.call(user: red_bag.user, red_bag: red_bag, money: red_bag.balance) red_bag.save end end end end end
class CreatePvArrayTests < ActiveRecord::Migration def change create_table :pv_array_tests do |t| t.references :pv_commission, index: true t.references :recombiner, index: true t.string :name t.string :megger_test t.string :comments t.string :voltage t.string :test_voltage t.string :pos t.string :neg t.string :test_number t.boolean :initial_verification t.string :inspector t.string :test_instruments t.string :combiner t.string :mfg t.string :combiner_exterior_pic t.string :combiner_interior_pic t.string :combiner_flir_pic t.timestamps end end end
class RemoveDefaultValueOnSellerWeightAndPackerBid < ActiveRecord::Migration def change change_column_default :sellers, :weight, nil change_column_default :sellers, :packerbid, nil end end
class AddFieldToContents < ActiveRecord::Migration def change add_column :contents, :campaign_goal, :string, :default => nil add_column :contents, :q_answer, :string end end
class AppCategorySerializer < ActiveModel::Serializer attributes :id, :name, :position end
Rails.application.routes.draw do devise_for :users resources :posts , :comments root 'posts#index' get '/name' =>'posts#user_post', as: :user_posts # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class Admin::ProductsController < ApplicationController before_action :authenticate_user! before_action :admin_required before_action :validate_search_key, only: [:search] layout "admin" def index @products = Product.order("created_at DESC").page(params[:page]).per(10) end def show @product = Product.find(params[:id]) @product_images = @product.product_images.all end def destroy @product = Product.find(params[:id]) @product.destroy redirect_to admin_products_path end def approve @product = Product.find(params[:id]) @product.agree! redirect_to :back end def unapprove @product = Product.find(params[:id]) @product.disagree! redirect_to :back end def search if @query_string.present? search_result = Product.joins(:user).ransack(@search_criteria).result(:distinct => true) @products = search_result.page(params[:page]).per(10) end end protected def validate_search_key @query_string = params[:keyword].gsub(/\\|\'|\/|\?/, "") if params[:keyword].present? @search_criteria = search_criteria(@query_string) end def search_criteria(query_string) { name_or_user_name_cont: query_string } end end
FactoryBot.define do factory :comment do body { '待ち時間をHPで随時発信しています。' } association :user association :task end end
# frozen_string_literal: true module Swagger::User class << self def included(base) base.include Swagger::Blocks base.send(:swagger_component) do schema :User do key :required, [:id, :email, :name] property :id do key :type, :integer key :format, :int64 end property :topic_count do key :type, :integer key :format, :int64 end property :email do key :type, :string end property :name do key :type, :string end end end end end end
class LaserGem < ApplicationRecord validates :name, length: { in: 2..90}, format: { without: /\s/, message: "must contain no spaces" } validates_uniqueness_of :name has_many :gem_dependencies has_many :dependencies, :through => :gem_dependencies has_many :gem_dependents, class_name: "GemDependency", foreign_key: :dependency_id has_many :dependents, :through => :gem_dependents, source: :laser_gem has_many :comments has_one :gem_spec has_one :gem_git , inverse_of: :laser_gem has_many :ownerships has_many :owners, :through => :ownerships, :foreign_key => "laser_gem_id", :source => "owner" belongs_to :category acts_as_taggable # Alias for acts_as_taggable_on :tags is_impressionable default_scope { order(total_rank: :desc) } def home_page gem_spec.home_page end def is_gem_owner?( user ) return false unless user self.ownerships.any? {|o| o.owner == user } end # # Add a gem as a dependency of this one. # def register_dependency(dep, version) GemDependency.create!( laser_gem: self, dependency: dep, version: version, ) self.reload end # # Remove a dependency # def remove_dependency(dep) GemDependency.where( laser_gem: self, dependency: dep, ).destroy_all self.reload end end
class School attr_accessor :name, :address, :number_of_students, :founding_years, :introduction_video_url, :introduction_statement def initialize(name, address, number_of_students,founding_years, introduction_video_url, introduction_statement) @name = name @address = address @number_of_students = number_of_students @founding_years = founding_years @introduction_video_url = introduction_video_url @introduction_statement = introduction_statement end def movie_start require "launchy" Launchy.open("#{@introduction_video_url}") end end # A学校用のインスタンスを作成 a_school = School.new("A学校", "東京都渋谷区..", 300, 100, "https://docs.ruby-lang.org/ja/latest/method/String/i/chars.html", "A学校は自然豊かな...") puts(a_school.name) puts(a_school.address) puts(a_school.number_of_students) puts(a_school.founding_years) puts(a_school.introduction_video_url) puts(a_school.introduction_statement) puts(a_school.instance_variables) a_school.movie_start
module Profile class BlogController < ApplicationController def index @user = User.find_by_username(params[:username]) @articles = @user.articles.order('created_at DESC').page(params[:page]).per(5) end def show @user = User.find_by_username(params[:username]) @article = @user.articles.find_by_slug(params[:slug]) end def new authenticate_user! @user = User.find_by_username(params[:username]) @article = Article.new redirect_to profile_new_article_path(current_user.username) if @user != current_user end def create authenticate_user! @user = User.find_by_username(params[:username]) @article = Article.new(article_params) @article.author = current_user if @article.save redirect_to profile_blog_path(current_user.username), notice: 'Article created successfully' else render :new end end def edit authenticate_user! @user = User.find_by_username(params[:username]) @article = @user.articles.find_by_slug(params[:slug]) redirect_to profile_new_article_path(current_user.username) if @user != current_user end def update authenticate_user! @user = User.find_by_username(params[:username]) @article = @article = @user.articles.find_by_slug(params[:slug]) if @article.update(article_params) redirect_to profile_blog_path(current_user.username), notice: 'Article updated successfully' else render :edit end end private def article_params params.require(:article).permit(:title, :slug, :body, :featured_image) end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "timveil/centos7-hdp-base" config.vm.box_check_update = true config.vm.hostname = "geomesa" config.vbguest.auto_update = true config.vbguest.no_remote = false config.vbguest.no_install = false config.vm.network "private_network", type: "dhcp" config.vm.define "geomesa" config.vm.provider "virtualbox" do |vb| vb.gui = false vb.cpus = 4 vb.name = "geomesa" vb.memory = "8192" end if Vagrant.has_plugin?("vagrant-proxyconf") config.proxy.http = "" config.proxy.https = "" config.proxy.no_proxy = "" end config.vm.provision :shell, :inline => ' export VERSION=1.3.4 sudo yum install epel-release -y sudo yum -y update sudo yum install -y java-1.8.0-openjdk mc vim maven cd /tmp wget http://repo.locationtech.org/content/repositories/geomesa-releases/org/locationtech/geomesa/geomesa-hbase-dist_2.11/$VERSION/geomesa-hbase-dist_2.11-$VERSION-bin.tar.gz ' end
class AddVersionToExercises < ActiveRecord::Migration def change add_column :exercises, :version, :integer, default: 1 end end
class BetUser < ApplicationRecord belongs_to :parlay, optional: true belongs_to :bet, dependent: :destroy belongs_to :user end
module JsonStructure class Null < Type def ===(value) value.nil? end end end
# encoding: UTF-8 class Rich @@allRich = [] attr_accessor :name, :fortune, :age, :born, :companies def initialize *args @name, @fortune, @age, @born, @companies = args @@allRich << self end def richer_than? other, year if other.class == self.class self.fortune[year] > other.fortune[year] else false end end def difference first_year, second_year (self.fortune[second_year]) - (self.fortune[first_year]) end def rank year richests = @@allRich.sort{|a,b| b.fortune[year] <=> a.fortune[year]} richests.index(self)+1 end def self.est year richest = @@allRich.sort{|a,b| a.fortune[year] <=> b.fortune[year]} richest.last end def self.rank year rich = @@allRich.sort {|a,b| a.fortune[year] <=> b.fortune[year]} rich end def self.younger (@@allRich.sort{|a,b| a.age <=> b.age}).first end def self.older (@@allRich.sort{|a,b| a.age <=> b.age}).last end def forecast year firstYear = fortune.keys.min lastYear = fortune.keys.max avg = difference(firstYear, lastYear) / 2.0 fortune[lastYear] + avg * (year-lastYear) end end gates = Rich.new "Gates", {2011 => 57, 2010 => 53, 2009 => 50}, 21, "Taquara", %w{TCA Azaléia} mittal = Rich.new "Mittal",{2011 => 31.1, 2010 => 28.7, 2009 => 19.3}, 25, "Santa Cruz do Sul", %w{Azaléia Afubra} eike = Rich.new "eike", {2011 => 30, 2010 => 27}, 26, "Santa Cruz do Sul", %w{Azaléia Afubra} slim = Rich.new "slim", {2011 => 04, 2010 => 53.5, 2009 => 35}, 30, "Santa Cruz do Sul", %w{Azaléia Afubra} #puts gates.difference 2009, 2011 #puts gates.richer_than? slim, 2010 puts gates.forecast 2013
require './src/token' require './src/tokenizer/built_ins' require './src/interpreter/processor' require './src/interpreter/errors' require './spec/contexts/processor' RSpec.describe Interpreter::Processor, 'built-ins' do include_context 'processor' describe '#execute' do # Output ############################################################################ it 'processes built-in print_stdout' do mock_lexer( Token.new(Token::PARAMETER, '「ほげ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::PRINT, sub_type: Token::FUNC_BUILT_IN), ) expect { execute } .to output('ほげ').to_stdout end it 'processes built-in display_stdout' do { ['1', Token::VAL_NUM] => '1', ['「あ」', Token::VAL_STR] => '"あ"', ['正', Token::VAL_TRUE] => 'true', ['偽', Token::VAL_FALSE] => 'false', ['無', Token::VAL_NULL] => 'null', ['配列', Token::VAL_ARRAY] => '{}', } .each do |(token_value, token_sub_type), output_value| mock_lexer( Token.new(Token::PARAMETER, token_value, particle: 'を', sub_type: token_sub_type), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DISPLAY, sub_type: Token::FUNC_BUILT_IN), ) expect { execute } .to output(output_value + "\n").to_stdout end mock_lexer( Token.new(Token::ASSIGNMENT, 'それ', sub_type: Token::VAR_SORE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '4', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3.2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '1.0', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'それ', particle: 'を', sub_type: Token::VAR_SORE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DISPLAY, sub_type: Token::FUNC_BUILT_IN), ) expect { execute } .to output("{0: 4, 1: 3.2, 2: 1}\n").to_stdout end it 'processes built-in dump' do mock_lexer( Token.new(Token::ASSIGNMENT, 'それ', sub_type: Token::VAR_SORE), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, 'それ', particle: 'を', sub_type: Token::VAR_SORE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DUMP, sub_type: Token::FUNC_BUILT_IN), ) expect { execute } .to output("\e[94m1\e[0m\n").to_stdout # dump with stop execution bang allow($stdout).to receive(:write) # suppress stdout mock_lexer( Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAR_SORE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DUMP, sub_type: Token::FUNC_BUILT_IN), Token.new(Token::BANG), Token.new(Token::PARAMETER, '「ほげ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::PRINT, sub_type: Token::FUNC_BUILT_IN), ) expect { execute } .to raise_error SystemExit end # Formatting ############################################################################ it 'processes built-in format' do # format array of parameters mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), # backslashes need to be doubly-doubled Token.new(Token::PARAMETER, '「あ〇い〇う\\〇え\\\\\\\\〇お」', particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FORMAT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq 'あ1い2う〇え\\3お' # format single value mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '「あ〇い\\〇う」', particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FORMAT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq 'あ1い〇う' # format number with various values mock_lexer( Token.new(Token::PARAMETER, '「〇( 詰め4桁。x詰め6桁)」', particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, '4.9', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FORMAT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq '   4.9xxxxx' # format with defaults mock_lexer( Token.new(Token::PARAMETER, '「〇(2桁)」', particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, '4649', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FORMAT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq '4649' # do not format if escaped mock_lexer( Token.new(Token::PARAMETER, '「〇\\(8桁)」', particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, '4649', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FORMAT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq '4649(8桁)' # do not format if escaped (quadrupley escaped leaves backslashes) mock_lexer( Token.new(Token::PARAMETER, '「〇\\\\\\\\(8桁)」', particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, '4649', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FORMAT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq '4649\\(8桁)' end it 'processes built-in round_up' do { '0桁' => 4649.4649, '1桁' => 4650, '2桁' => 4650, '3桁' => 4700, '4桁' => 5000, '5桁' => 10_000, '小数第0位' => 4649.4649, '小数第1位' => 4649.5, '小数第2位' => 4649.47, '小数第3位' => 4649.465, '小数第4位' => 4649.4649, '小数第5位' => 4649.4649, }.each do |precision, result| mock_lexer( Token.new(Token::PARAMETER, '4649.4649', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, "「#{precision}」", particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::ROUND_UP, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq result end end it 'processes built-in round_down' do { '0桁' => 4649.4649, '1桁' => 4649, '2桁' => 4640, '3桁' => 4600, '4桁' => 4000, '5桁' => 0, '小数第0位' => 4649.4649, '小数第1位' => 4649.4, '小数第2位' => 4649.46, '小数第3位' => 4649.464, '小数第4位' => 4649.4649, '小数第5位' => 4649.4649, }.each do |precision, result| mock_lexer( Token.new(Token::PARAMETER, '4649.4649', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, "「#{precision}」", particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::ROUND_DOWN, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq result end end it 'processes built-in round_nearest' do { '0桁' => 4649.4649, '1桁' => 4649, '2桁' => 4650, '3桁' => 4600, '4桁' => 5000, '5桁' => 0, '小数点第0位' => 4649.4649, '小数点第1位' => 4649.5, '小数点第2位' => 4649.46, '小数点第3位' => 4649.465, '小数点第4位' => 4649.4649, '小数点第5位' => 4649.4649, }.each do |precision, result| mock_lexer( Token.new(Token::PARAMETER, '4649.4649', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, "「#{precision}」", particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::ROUND_NEAREST, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq result end end it 'processes built-in cast_to_n' do { '5' => { sub_type: Token::VAL_NUM, result: 5 }, '4.6' => { sub_type: Token::VAL_NUM, result: 4.6 }, '「4.9」' => { sub_type: Token::VAL_STR, result: 4.9 }, '配列' => { sub_type: Token::VAL_ARRAY, result: 0 }, '真' => { sub_type: Token::VAL_TRUE, result: 1 }, '偽' => { sub_type: Token::VAL_FALSE, result: 0 }, '無' => { sub_type: Token::VAL_ARRAY, result: 0 }, }.each do |parameter, test| mock_lexer( Token.new(Token::PARAMETER, parameter, particle: 'を', sub_type: test[:sub_type]), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::CAST_TO_N, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq test[:result] end end it 'processes built-in cast_to_i' do { '5' => { sub_type: Token::VAL_NUM, result: 5 }, '4.6' => { sub_type: Token::VAL_NUM, result: 4 }, '「4.9」' => { sub_type: Token::VAL_STR, result: 4 }, '配列' => { sub_type: Token::VAL_ARRAY, result: 0 }, '真' => { sub_type: Token::VAL_TRUE, result: 1 }, '偽' => { sub_type: Token::VAL_FALSE, result: 0 }, '無' => { sub_type: Token::VAL_ARRAY, result: 0 }, }.each do |parameter, test| mock_lexer( Token.new(Token::PARAMETER, parameter, particle: 'を', sub_type: test[:sub_type]), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::CAST_TO_I, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq test[:result] end end # String / Array Operations ############################################################################ it 'processes built-in push' do # push array mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '3', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::PUSH, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array [1, 2, 3] expect(sore).to eq sd_array [1, 2, 3] # push string mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「ほげ」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「ふが」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::PUSH, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'ほげふが' expect(sore).to eq 'ほげふが' end it 'processes built-in pop' do # pop array mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::POP, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array [1, 2] expect(sore).to eq 3 # pop string mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「ほげげ」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::POP, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'ほげ' expect(sore).to eq 'げ' end it 'processes built-in unshift' do # unshift array mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::UNSHIFT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array [1, 2, 3] expect(sore).to eq sd_array [1, 2, 3] # unshift string mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「げ」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「ほ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::UNSHIFT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'ほげ' expect(sore).to eq 'ほげ' end it 'processes built-in shift' do # shift array mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SHIFT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array [2, 3] expect(sore).to eq 1 # shift string mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「ほげ」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SHIFT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'げ' expect(sore).to eq 'ほ' end it 'processes built-in remove' do # remove from array mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '2', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::REMOVE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array('0' => 1, '2' => 2) expect(sore).to eq 2 # remove from string mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「ほげげ」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「げ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::REMOVE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'ほげ' expect(sore).to eq 'げ' end it 'processes built-in remove_all' do # remove all from array mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '2', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::REMOVE_ALL, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array('0' => 1) expect(sore).to eq sd_array('0' => 2, '1' => 2) # remove all from string mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「ほげげ」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「げ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::REMOVE_ALL, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'ほ' expect(sore).to eq %w[げ げ] end it 'processes built-in concat' do # concat arrays mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::ASSIGNMENT, 'フガ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '4', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '5', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '6', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, 'フガ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::CONCATENATE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array [1, 2, 3] expect(variable('フガ')).to eq sd_array [4, 5, 6] expect(sore).to eq sd_array [1, 2, 3, 4, 5, 6] # concat strings mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「ほげ」', sub_type: Token::VAL_STR), Token.new(Token::ASSIGNMENT, 'フガ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「ふが」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, 'フガ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::CONCATENATE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'ほげ' expect(variable('フガ')).to eq 'ふが' expect(sore).to eq 'ほげふが' end it 'processes built-in join' do mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '「あ」', sub_type: Token::VAL_STR), Token.new(Token::COMMA), Token.new(Token::RVALUE, '真', sub_type: Token::VAL_TRUE), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「、」', particle: 'で', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::JOIN, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq '1、あ、はい' end it 'processes built-in split' do # split arrays mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '「あ」', sub_type: Token::VAL_STR), Token.new(Token::COMMA), Token.new(Token::RVALUE, '真', sub_type: Token::VAL_TRUE), Token.new(Token::COMMA), Token.new(Token::RVALUE, '偽', sub_type: Token::VAL_FALSE), Token.new(Token::COMMA), Token.new(Token::RVALUE, '無', sub_type: Token::VAL_NULL), Token.new(Token::COMMA), Token.new(Token::RVALUE, '正', sub_type: Token::VAL_TRUE), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, 'はい', particle: 'で', sub_type: Token::VAL_TRUE), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SPLIT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq sd_array [sd_array([1, 'あ']), sd_array([false, nil]), sd_array] # split strings mock_lexer( Token.new(Token::PARAMETER, '「little red hat」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, '「 」', particle: 'で', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SPLIT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq sd_array %w[little red hat] end it 'processes built-in slice' do # slice arrays mock_lexer( # make array {0: 1, 1: 2, 2: 3, え: 4, 4: 5, 5: 6} Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '「え」', sub_type: Token::KEY_NAME), Token.new(Token::RVALUE, '4', sub_type: Token::VAL_NUM), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '5', sub_type: Token::KEY_INDEX), Token.new(Token::RVALUE, '5', sub_type: Token::VAL_NUM), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '「5」', sub_type: Token::KEY_NAME), Token.new(Token::RVALUE, '6', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '2', particle: 'から', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '4', particle: 'まで', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SLICE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq sd_array('0' => 1, '1' => 2, '5' => 6) expect(sore).to eq sd_array('0' => 3, 'え' => 4, '1' => 5) # slice strings mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「あいうえおかきくけこ」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '2', particle: 'から', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '4', particle: 'まで', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SLICE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 'あいかきくけこ' expect(sore).to eq 'うえお' # boundaries clamp mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「あいうえお」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '-1', particle: 'から', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '100', particle: 'まで', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SLICE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq '' expect(sore).to eq 'あいうえお' end it 'processes built-in find' do # find in array (string key) mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '配列', sub_type: Token::VAL_ARRAY), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '「キー名」', sub_type: Token::KEY_NAME), Token.new(Token::RVALUE, '「ふが」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'で', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「ふが」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FIND, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq 'キー名' # find in array (numeric key) mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::PARAMETER, 'ホゲ', particle: 'で', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '2', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FIND, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq 1 # find in string mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「あいうえお」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'で', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「う」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FIND, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq 2 # return null on not found mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '「あいうえお」', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'ホゲ', particle: 'で', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「か」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::FIND, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to be_nil end it 'processes built-in sort' do # creates an array {0: 2, 1: 1, 2: 3, 6: true, 4: "い", "ほげ": "う", 4.6: "あ"} array_tokens = [ Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ARRAY_BEGIN), Token.new(Token::RVALUE, '2', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '1', sub_type: Token::VAL_NUM), Token.new(Token::COMMA), Token.new(Token::RVALUE, '3', sub_type: Token::VAL_NUM), Token.new(Token::ARRAY_CLOSE), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '7', sub_type: Token::KEY_INDEX), Token.new(Token::RVALUE, '真', sub_type: Token::VAL_TRUE), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '5', sub_type: Token::KEY_INDEX), Token.new(Token::RVALUE, '「い」', sub_type: Token::VAL_STR), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '「ほげ」', sub_type: Token::KEY_NAME), Token.new(Token::RVALUE, '「う」', sub_type: Token::VAL_STR), Token.new(Token::POSSESSIVE, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::ASSIGNMENT, '「4.6」', sub_type: Token::KEY_NAME), Token.new(Token::RVALUE, '「あ」', sub_type: Token::VAL_STR), ] # ascending order mock_lexer( *array_tokens, Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「昇順」', particle: 'で', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SORT, sub_type: Token::FUNC_BUILT_IN), ) execute result = sore.to_a { '1.0' => 1.0, '0.0' => 2.0, '2.0' => 3.0, '4.6' => 'あ', '4.0' => 'い', 'ほげ' => 'う', '6.0' => true, }.each do |expected_key, expected_value| actual = result.shift expect(actual[0]).to eq expected_key expect(actual[1]).to eq expected_value end # descending order mock_lexer( *array_tokens, Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '「降順」', particle: 'で', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SORT, sub_type: Token::FUNC_BUILT_IN), ) execute result = sore.to_a { '6.0' => true, 'ほげ' => 'う', '4.0' => 'い', '4.6' => 'あ', '2.0' => 3.0, '0.0' => 2.0, '1.0' => 1.0, }.each do |expected_key, expected_value| actual = result.shift expect(actual[0]).to eq expected_key expect(actual[1]).to eq expected_value end end # Math ############################################################################ it 'processes built-in add' do mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '7', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '3', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::ADD, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 7 expect(sore).to eq 10 end it 'processes built-in subtract' do mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '7', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, 'ホゲ', particle: 'から', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '3', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SUBTRACT, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 7 expect(sore).to eq 4 end it 'processes built-in multiply' do mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '7', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, 'ホゲ', particle: 'に', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '3', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::MULTIPLY, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 7 expect(sore).to eq 21 end it 'processes built-in divide' do mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '7', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '3', particle: 'で', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DIVIDE, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 7 expect(sore).to eq 7.0 / 3.0 end it 'processes built-in mod' do mock_lexer( Token.new(Token::ASSIGNMENT, 'ホゲ', sub_type: Token::VARIABLE), Token.new(Token::RVALUE, '7', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, 'ホゲ', particle: 'を', sub_type: Token::VARIABLE), Token.new(Token::PARAMETER, '3', particle: 'で', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::MODULUS, sub_type: Token::FUNC_BUILT_IN), ) execute expect(variable('ホゲ')).to eq 7 expect(sore).to eq 1 end # Misc ############################################################################ it 'processes built-in throw' do mock_lexer( Token.new(Token::PARAMETER, '「ほげ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::THROW, sub_type: Token::FUNC_BUILT_IN), ) allow($stderr).to receive(:write) # suppress stderr expect { execute } .to raise_error Interpreter::Errors::CustomError end it 'processes built-in srand and rand' do mock_lexer( Token.new(Token::PARAMETER, '4649', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SRAND, sub_type: Token::FUNC_BUILT_IN), Token.new(Token::PARAMETER, '0', particle: 'から', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '100000', particle: 'まで', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::RAND, sub_type: Token::FUNC_BUILT_IN), ) execute expect(sore).to eq 90_379 end # Boolean Casting ############################################################################ # Only covers v1.0.0 built-ins. ############################################################################ [ { tokens: [ Token.new(Token::PARAMETER, '「ほげ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::PRINT, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DISPLAY, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DUMP, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, # NOTE: no test for 投げる because it throws an error anyway { tokens: [ Token.new(Token::PARAMETER, '配列', particle: 'に', sub_type: Token::VAL_ARRAY), Token.new(Token::PARAMETER, '配列', particle: 'を', sub_type: Token::VAL_ARRAY), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::CONCATENATE, sub_type: Token::FUNC_BUILT_IN), ], result: false, }, { tokens: [ Token.new(Token::PARAMETER, '「あ」', particle: 'から', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, 'あ', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::REMOVE, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '「ああ」', particle: 'から', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, '「あ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::REMOVE_ALL, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '配列', particle: 'に', sub_type: Token::VAL_ARRAY), Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::PUSH, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '「あ」', particle: 'から', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::POP, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '「」', particle: 'に', sub_type: Token::VAL_STR), Token.new(Token::PARAMETER, '「あ」', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::UNSHIFT, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '「あ」', particle: 'から', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SHIFT, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '1', particle: 'に', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::ADD, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '1', particle: 'から', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::SUBTRACT, sub_type: Token::FUNC_BUILT_IN), ], result: false, }, { tokens: [ Token.new(Token::PARAMETER, '999', particle: 'に', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '0', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::MULTIPLY, sub_type: Token::FUNC_BUILT_IN), ], result: false, }, { tokens: [ Token.new(Token::PARAMETER, '10', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '2', particle: 'で', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DIVIDE, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, { tokens: [ Token.new(Token::PARAMETER, '7', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '3', particle: 'で', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::MODULUS, sub_type: Token::FUNC_BUILT_IN), ], result: true, }, ].each do |test| built_in = test[:tokens].last.content it "processes built-in #{built_in} with boolean cast" do mock_lexer(*test[:tokens], Token.new(Token::QUESTION)) allow($stdout).to receive(:write) # suppress stdout execute expect(sore).to eq test[:result] end end end end
class TagsController < ApplicationController respond_to :json def index @tags = Tag.all respond_to do |format| format.json { render :json => @tags.to_json } end end def show @tag = Tag.find(params[:id]) respond_to do |format| format.json { render :json => @tag.to_json } end end def create @tag = Tag.new(tag_params) respond_to do |format| if @tag.save format.json { render :json => @tag.to_json, :status => :created, :location => @tag } else format.json { render :json => @tag.errors, :status => :unprocessable_entity } end end end def update @tag = Tag.find(params[:id]) respond_to do |format| if @tag.update_attributes(tag_params) format.json { head :ok } else format.json { render :json => @tag.errors, :status => :unprocessable_entity } end end end def destroy @tag = Tag.find(params[:id]) @tag.destroy respond_to do |format| format.json { head :ok } end end protected def tag_params params.require(:tag).permit(:name) end end
class CartController < ApplicationController before_action :authenticate_user! def add # get the Id of the product id = params[:id] # if the cart is already been created, use existing cart else create a blank cart if session[:cart] then cart = session[:cart] else session[:cart] = {} cart = session[:cart] end #If the product is already added it increments by 1 else product set to 1 if cart[id] then cart[id] = cart[id] + 1 else cart[id]= 1 end redirect_to :action => :index end def index # passes a cart to display if session[:cart] then @cart = session[:cart] else @cart = {} end end ##delete Item## def remove id = params[:id] cart = session[:cart] cart.delete id redirect_to :root end ##clear cart## def clearCart # clear cart and remove all items session[:cart] = nil redirect_to :action => :index end ##decrease the quantity## def decrease id = params[:id] cart = session[:cart] if cart[id] == 1 then cart.delete id else cart[id] = cart[id] - 1 end #Taking us to cart index[view] page redirect_to :action => :index end ##createOrder## def createOrder #step 1 find out who is actually placing the order @user = User.find(current_user.id) # Step 2 actually make the order we wnt to keep in our database @order = @user.orders.build(:order_date => DateTime.now, :status => "Pending") @order.save # Step 3 - Take all items from current cart and associate them with the order @cart = session[:cart] || {} # This gets the content from the current shopping cart @cart.each do | id, quantity| item = Item.find_by_id(id) @orderitem = @order.orderitems.build(:item_id => item.id, :title => item.title, :quantity => quantity, :price => item.price) @orderitem.save end @orders = Order.all @orderitems = Orderitem.where(order_id: Order.last) session[:cart] = nil end end
module Pod class Command class X < Command class Repo < X self.summary = 'Opens pods dir.' self.description = <<-DESC Opens pods. DESC self.arguments = [ CLAide::Argument.new('NAME', true), ] def self.options [ ['--terminal', 'Use terminal open pod'] ].concat(super) end def initialize(argv) @name = argv.shift_argument @wipe_terminal = argv.flag?('terminal') super end def run pods = Pod::X::Sandbox::workspace::all_pods if !@name.nil? && @name.size > 0 pods = pods.select{ |pod| pod.name == @name } end open_pods pods end private extend Executable executable :open def open_pods pods return if (pods.nil? || pods.size <= 0) choices = Array::new pods.each do |pod| choice = pod.name unless pod.branch.nil? choice += " (#{pod.branch})".red end unless pod.project.nil? choice += " => project: #{pod.project}" end choice += " => path: #{pod.location_url}" choices << choice end begin if choices.size == 1 index = 0 else index = UI.choose_from_array(choices, 'Which item do you?') end url = pods[index].location_url open_url! url rescue => exception UI.puts '[!] Pod::X '.magenta + "#{exception}".red end end def open_url! url ter = sel_ter if @wipe_terminal && ter open! ['-a', ter, url] else open! [url] end end def sel_ter ters = ['/Applications/iTerm.app', '/System/Applications/Utilities/Terminal.app'] ters.each do |t| path = Pathname(t) return path if path.exist? end nil end end end end end
class EricWeixin::Redpack < ActiveRecord::Base self.table_name = 'weixin_redpacks' belongs_to :redpack_order, foreign_key: 'weixin_redpack_order_id' STATUS = { "SENDING" => "发放中", "SENT" => "已发放待领取", "FAILED" => "发放失败", "RECEIVED" => "已领取", "REFUND" => "已退款" } def self.create_redpack options self.transaction do packs = EricWeixin::Redpack.where weixin_redpack_order_id: options[:weixin_redpack_order_id], openid: options[:openid] return packs[0] unless packs.blank? redpack = self.new status: options[:status], openid: options[:openid], amount: options[:amount], rcv_time: options[:rcv_time], weixin_redpack_order_id: options[:weixin_redpack_order_id] redpack.save! redpack end end end
require 'rails_helper' describe WebinarsController, type: :controller do describe '#index' do context 'for not logged in user' do it 'redirects to login page' do get :index expect(response).to redirect_to(auth_path) end end end end
class Spree::AdvancedReport::DailyDetailsReport < Spree::AdvancedReport::IncrementReport attr_accessor :date, :products, :shipments, :tax_adjustments, :price_adjustments, :other_adjustments, :orders, :payments def column "Detailed Units" end def initialize(params) super(params) results = details_for_date(date) date = params[:date] ? Date.parse(params[:date]) : Date.today self.date = date # Update the accessor values results.each{|k,v| self.send("#{k}=", v)} end def details_for_date(date) date = params[:date] ? Date.parse(params[:date]) : Date.today conditions = {updated_at: date.beginning_of_day..date.end_of_day, state: 'completed'} payments = Spree::Payment.joins(:order).where(conditions).where('spree_orders.completed_at is not null').includes(source: [], order: [:shipments, :adjustments]) orders = payments.collect(&:order).uniq shipments = orders.collect(&:shipments).flatten adjustment_ids = orders.collect(&:adjustments).flatten.collect(&:id) tax_adjustments = Spree::Adjustment.tax.where(id: adjustment_ids) price_adjustments = Spree::Adjustment.price.where(id: adjustment_ids) other_adjustments = Spree::Adjustment.where(id: adjustment_ids) - tax_adjustments - price_adjustments - shipments.collect(&:adjustment) # adjustments = orders.collect(&:adjustments).flatten.select{|a| a.source_type != 'Spree::Shipment'} line_items = orders.collect(&:line_items).flatten products = line_items.reduce({}) do |memo, item| memo[item.variant] ||= {amount: 0, quantity: 0} memo[item.variant][:amount] += item.amount memo[item.variant][:quantity] += item.quantity memo end {products: products, shipments: shipments, tax_adjustments: tax_adjustments, price_adjustments: price_adjustments, other_adjustments: other_adjustments, orders: orders, payments: payments} end # This is a placeholder for logic that determines how many items in an order were actually shipped. # It may never be used again def items_shipped_from_an_order # For each order, determine how many items = {} orders.each do |o| shipped_variants = o.inventory_units.collect{|i| i.variant} o.line_items.each do |i| variant = i.variant quantity = shipped_variants.count(variant) items[variant] ||= {count: 0, price: 0} items[variant][:count] += 1 items[variant][:price] += i.price * quantity end end [items, shipments, adjustments] end end
FactoryGirl.define do factory :book do title "Test Book" author "Test Author" pub_date 2008 genre "nonfiction" format "pb" publisher "Basic Books" isbn "9780465026562" summary "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor, asperiores neque porro." end end
class Booking < ApplicationRecord belongs_to :teacher, class_name: "User", foreign_key: "teacher_id", optional: true belongs_to :student, class_name: "User", foreign_key: "student_id", optional: true # Stripe has_many :sales validates_numericality_of :price, greater_than: 50, message: "must be at least 50 cents" end
puts expand = defined?( expand ) ? expand : true =begin let's break this down .. expand = if defined?(expand) expand else true end puts expand .. defined? is an operator which IN THIS case would have returned a non-nil value('local-variable' mostly) had expand been defined before in the code. Since it is not, the if block will evaluate to true. but now there's a rule with reference to defined? that says: "Assignment to a local variable will, however, have the result of initializing the variable to nil by virtue of the assignment expression itself" (From ruby-doc) Hence the output which is nil. Sources: * http://www.ruby-doc.org/docs/ProgrammingRuby/tut_expressions.html#definedandorandnot * http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-defined-3F =end
require_relative('../identifier_expr') require_relative('../fake_expr') require_relative('../bin_expr/sub_expr') require_relative('../../error_handler') require_relative('../../error/expression_not_assignable_error') class PostDecExpr < IdentifierExpr def initialize(expr, lineno) if expr.is_a? IdentifierExpr super(expr.id, lineno) else ErrorHandler.instance.register_error(msg: ExpressionNotAssignableError.new.message, lineno: lineno) super(nil, lineno) end @expr = expr end def code(scope) if @id.nil? return '', '' end constant_expr = ConstantExpr.build_constant(type(scope), 1) expr_type = type(scope) expr_code, expr_val = super(scope) fake_expr = FakeExpr.new('', expr_val, expr_type) begin assign_code = AssignmentExpr.new(@id, SubExpr.new(fake_expr, constant_expr, @lineno), @lineno).code(scope)[0] rescue LanguageError => msg ErrorHandler.instance.register_error(msg: msg, lineno: @lineno) return '', '' end return expr_code + assign_code, expr_val end end
ReportsKit.configure do |config| config.custom_methods = { format_percentage: -> (value) { "#{value.round(0)}%" }, add_label_link: -> (data:, properties:, context_record:) { data[:entities].each do |entity| entity.label = "<a href='#'>#{entity.label}</a> Bar" if entity.label end data }, add_label_suffix: -> (data:, properties:, context_record:) { data[:entities].each do |entity| entity.label = "#{entity.label} Foo" if entity.label end data }, add_context_record_suffix: -> (data:, properties:, context_record:) { data[:entities].each do |entity| entity.label = "#{entity.label} #{context_record}" if entity.label end data }, empty_result_set_for_relation: -> (relation) { relation.where('0 = 1') }, prepend_column: -> (data:, properties:, context_record:) { values = data[:entities].map do |entity| value = entity.instance.is_a?(Date) ? entity.instance.mday : nil ReportsKit::Value.new(value, value) end new_dataset = { entity: ReportsKit::Entity.new('day_of_month', 'Day of Month', 'day_of_month'), values: values } data[:datasets] = [new_dataset] + data[:datasets] data }, all_repo_ids: -> (dimension_keys:, properties:, context_record:) { Repo.pluck(:id) } } end
class RepliesController < ApplicationController respond_to :json before_filter :auth_user, except: [:show] before_filter :post_group_member, only: [:create, :post_replies] before_filter :correct_receiver, only: [:create] before_filter :correct_viewer, only: [:post_replies] before_filter :reply_author, only: [:destroy, :update] after_filter :clear_all_data # params: access_token, post_id, content, location, lat, lng # correct_receiver's right def create content = params[:content] location = params[:location] lat = params[:lat] lng = params[:lng] @reply = @current_user.replies.new(content: content, location: location, lat: lat, lng: lng) @reply.post_id = @post.id if @reply.save respond_with(@reply, only: [:id, :content, :location, :lat, :lng, :created_at]) else render_error(404, request.path, 20301, @reply.errors.as_json) end end # params: access_token, reply_id, reply[variable] # author's right def update if @reply.update_attributes(params[:reply]) respond_with @reply else render_error(401, request.path, 20302, "Failed to edit reply.") end end # params: access_token, reply_id # author's right def destroy if @reply.destroy render json: {result: 1} else render json: {result: 0} end end # params: access_token, post_id # authorized member's right def post_replies @replies = @post.replies render_results(@replies) end # testing def show @reply = Reply.find(params[:id]) if @reply respond_with(@reply, only: [:lat, :lng, :address, :content]) else render_error(404, request.path, 30000, "Invalid reply") end end private def correct_receiver @receivers = @group.users if @receivers.include?(@current_user) return true else render_error(404, request.path, 20300, "Invalid receiver") return false end end def post_group_member @post = Post.find(params[:post_id]) @group = @post.group if @current_user.is_member?(@group) return true else render_error(404, request.path, 20300, "Current user is not in the post's group.") return false end end def reply_author @reply = Reply.find(params[:reply_id]) if @current_user.is_author?(@reply) return true else render_error(404, request.path, 20300, "Not the reply's author.") return false end end def correct_viewer @viewers = @group.authorized_users if @viewers.include?(@current_user) return true else render_error(404, request.path, 20300, "Invalid viewer") return false end end end
class ChargesController < ApplicationController def new @charity = Charity.find_by_domain( params[ :charity_id ] ) @pages = @charity.pages end def create # Amount in cents @charity = Charity.find_by_domain( params[ :charity_id ] ) @amount = params[ :stripeAmount ] @donation = @charity.donations.create( amount: ( params[ :stripeAmount ].to_f / 100 ), token: params[ :stripeToken ], email: params[ :stripeEmail ] ) if @donation.save! customer = Stripe::Customer.create( :email => params[ :stripeEmail ], :card => params[ :stripeToken ] ) charge = Stripe::Charge.create( :customer => customer.id, :amount => @amount, :description => "Charity hosting donation", :currency => 'EUR' ) flash[ :success ] = true flash[ :overhead ] = "Transaction successful." else flash[ :overhead ] = "Transaction failed." end redirect_to :back rescue Stripe::CardError => error redirect_to :back, flash: { overhead: error } end end
module Feature module TableSupport def first_row nth_row(1) end def second_row nth_row(2) end def nth_row(num) find("table tbody tr:nth-child(#{num})") end end end
class Card < ApplicationRecord has_many :game_cards has_many :games, through: :game_cards end
FactoryBot.define do factory :todo do title {Faker::Lorem.characters(10)} end end
require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'rake' require 'jeweler' Jeweler::Tasks.new do |gem| # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options gem.name = "bio-gem" gem.homepage = "http://github.com/helios/bioruby-gem" gem.license = "MIT" gem.summary = %Q{Biogem is a software generator for Ruby in bioinformatics} gem.description = %Q{Biogem is a software generator for those bioinformaticans who want to start coding an application or a library for using/extending BioRuby core library and sharing it through rubygems.org . The basic idea is to simplify and promote a modular approach to bioinformatics software development} gem.email = "ilpuccio.febo@gmail.com" gem.authors = ["Raoul J.P. Bonnal", "Pjotr Prins"] # Include your dependencies below. Runtime dependencies are required when using your gem, # and development dependencies are only needed for development (ie running rake tasks, tests, etc) #gem.version='0.0.1' gem.rdoc_options << '--main' << 'README' << '--line-numbers' gem.required_ruby_version = ">= 1.9.3" gem.extra_rdoc_files = ['LICENSE.txt', 'README.rdoc','Tutorial.rdoc'] end # # Ricordati ti aggiungere README e Tutorial # # spec.extra_rdoc_files = ['README', 'doc/user-guide.txt'] # # def extra_rdoc_files # @extra_rdoc_files ||= [] # end # Jeweler::RubygemsDotOrgTasks.new require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.libs << 'lib' << 'test' # test.pattern = 'test/**/test_*.rb' breaks in Ruby 1.9.3 test.test_files = Dir.glob("test/**/test_*.rb") test.verbose = true end # No proper rcov support in 1.9 # # require 'rcov/rcovtask' # Rcov::RcovTask.new do |test| # test.libs << 'test' # test.pattern = 'test/**/test_*.rb' # test.verbose = true # end task :default => :test require 'rdoc/task' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "bio-gem #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('Tutorial.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end
class Bike < ActiveRecord::Base acts_as_loggable attr_accessible :shop_id, :serial_number, :bike_brand_id, :bike_model_id, :model, :color, :bike_style_id, :seat_tube_height, :top_tube_length, :bike_wheel_size_id, :value, :bike_condition_id, :bike_purpose_id, :photo has_many :transactions has_one :owner, :class_name => 'User' has_one :task_list, :as => :item, :dependent => :destroy belongs_to :bike_brand belongs_to :bike_model belongs_to :bike_style belongs_to :bike_condition belongs_to :bike_purpose belongs_to :bike_wheel_size has_attached_file :photo, :styles => {:thumb => '100x100>'} validates :shop_id, :presence => true, :uniqueness => true, :numericality => { :only_integer => true } validates :serial_number, :length => { :minimum => 3 } validates :model, :length => { :maximum => 50 } validates :bike_brand_id, :presence => true, :numericality => { greater_than: 0, message: "is not a valid brand" } #validates :color, :presence => true validates :bike_style_id, :presence => true, :numericality => { greater_than: 0, message: "is not a valid style" } validates :seat_tube_height, :presence => true, :numericality => true validates :bike_wheel_size_id, :presence => true, :numericality => { greater_than: 0, message: "is not a valid wheel size" } validates :bike_condition_id, :presence => true, :numericality => { greater_than: 0, message: "is not a valid condition" } validates :bike_purpose_id, :presence => true, :numericality => { greater_than: 0, message: "is not a valid purpose" } validates_attachment :photo, :content_type => {:content_type => %w{ image/jpeg image/gif image/png }}, :file_name => {:matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]} self.per_page = 15 after_create :create_task_list def brand self.bike_brand end def style self.bike_style end def condition self.bike_condition end def purpose self.bike_purpose end def wheel_size self.bike_wheel_size end def to_s "#{brand} - #{model} - #{style}" end def create_task_list TaskList.create( item_id: self.id, item_type: self.class.to_s, name: "Safety Checklist") end end
# # Cookbook:: jnj_chef_stack # Recipe:: standalone # # Copyright:: 2017, The Authors, All Rights Reserved. include_recipe 'chef_infra' # See if an automate exists yet before setting the data collector url. automate_fqdn_array = search_for_nodes(%(chef_environment:"#{node.chef_environment}") + ' AND recipes:chef_infra\:\:automate').map { |node| node['fqdn'] } node.default['chef-server']['standalone']['data_collector']['root_url'] = "https://#{automate_fqdn_array[0]}/data-collector/v0/" unless automate_fqdn_array.empty? # See if a supermarket exists yet before setting the oc_id information. supermarket_fqdn_array = search_for_nodes(%(chef_environment:"#{node.chef_environment}") + ' AND recipes:chef_infra\:\:supermarket').map { |node| node['fqdn'] } unless supermarket_fqdn_array.empty? node.default['chef-server']['standalone']['oc_id']['applications']['supermarket'] = {} node.default['chef-server']['standalone']['oc_id']['applications']['supermarket']['redirect_uri'] = "https://#{supermarket_fqdn_array[0]}/auth/chef_oauth2/callback" end # Merge the standalone and default configuration attributes, with the standalone winning any conflict. node.default['chef-server']['configuration'] = Chef::Mixin::DeepMerge.deep_merge(node.default['chef-server']['standalone'], node.default['chef-server']['configuration']) include_recipe 'chef_infra::_server' ruby_block 'gather automate secrets' do block do automate = { 'validator_pem' => ::File.read("/etc/opscode/orgs/#{node['chef_stack']['chef_org']}-validation.pem"), 'user_pem' => ::File.read(node['chef_stack']['chef_client_key_path']), 'builder_pem' => ::File.read(node['chef_stack']['builder_key_path']), } unless supermarket_fqdn_array.empty? # 'builder_pub' => "ssh-rsa #{[builder_key.to_blob].pack('m0')}", supermarket_ocid = JSON.parse(::File.read('/etc/opscode/oc-id-applications/supermarket.json')) automate.merge('supermarket_oauth2_app_id' => supermarket_ocid['uid'], 'supermarket_oauth2_secret' => supermarket_ocid['secret'], 'supermarket_fqdn' => URI(supermarket_ocid['redirect_uri']).host) end write_env_secret('automate_secrets', automate) end action :run only_if { node['chef_stack']['is_chef_master'] } end
# Numbers to Commas Solo Challenge # I spent [2] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented in the file. # 0. Pseudocode # What is the input? #The input is a postive integer # What is the output? (i.e. What should the code return?) #The output is a string of positive integers with the commas in the correct place. # What are the steps needed to solve the problem? # make sure that no commas are added to integers with <4 digits # add a comma after each set of 3 digits # turn the integer into a string # 1. Initial Solution # def separate_comma(num) # num_s = num.to_s # if num <= 999 # return num.to_s # elsif num <= 9999 # return num_s[0] + "," + num_s[1] + num_s[2] + num_s[3] # elsif num <= 99999 # return num_s[0] + num_s[1] + "," + num_s[2] + num_s[3] + num_s[4] # elsif num <= 999999 # return num_s[0] + num_s[1] + num_s[2] + "," + num_s[3] + num_s[4] + num_s[5] # elsif num <= 9999999 # return num_s[0] + "," + num_s[1] + num_s[2] + num_s[3] + "," + num_s[4] + num_s[5] + num_s[6] # elsif num <= 99999999 # return num_s[0] + num_s[1] + "," + num_s[2] + num_s[3] + num_s[4] + "," + num_s[5] + num_s[6] + num_s[7] # end # end # 2. Refactored Solution def separate_comma(num) num_s = num.to_s.reverse letternums = num_s.split("") empty = "" if num <= 999 return num.to_s end idx = 0 while idx < letternums.length empty += letternums[idx] if empty.length == 3 || empty.length == 7 empty += "," unless idx == letternums.length - 1 end idx += 1 end empty.reverse end # 3. Reflection =begin What was your process for breaking the problem down? What different approaches did you consider? *I wanted my first solution to be really really simple so that I could get a feel for how the problem worked at its very core. I couldn't think of a better way to do it than to add a comma after every 3 digits, starting from the last digit and moving toward the front. Was your pseudocode effective in helping you build a successful initial solution? *It helped me think of the most basic steps I needed to take in solving the problem. Coming up with a really simple solution didn't take long, it was the second solution that ate up almost all the 2 hours I spent on it. What new Ruby method(s) did you use when refactoring your solution? Describe your experience of using the Ruby documentation to implement it/them (any difficulties, etc.). Did it/they significantly change the way your code works? If so, how? *I didn't really use any new methods except #reverse. I wanted to keep the logic as simple as possible (I think I still failed in that endeavor though). I was looking for a simple method that I could use for my "unless" statement that would check to see if an element was the last element to be iterated in the array. How did you initially iterate through the data structure? *I tried it with a .each loop, but that didn't work out so well, so I simplified and used a while loop. Do you feel your refactored solution is more readable than your initial solution? Why? *It's certainly more elegent than my initial solution, but I don't know about readable, haha. My first solution was essentially the same code written over and over, with a few changes. The second is a little bit better, but I wish I could get it to be neater. =end
require 'rails_helper' feature 'Admin register subsidiary' do scenario 'must be sign in' do visit root_path click_on 'Filiais' expect(current_path).to eq new_user_session_path end scenario 'from index page' do user = User.create!(name: 'João Almeida', email: 'joao@gmail.com', password: '123456') login_as(user, scope: :user) visit root_path click_on 'Filiais' expect(page).to have_link('Registrar uma nova filial', href: new_subsidiary_path) end scenario 'sucessfully' do user = User.create!(name: 'João Almeida', email: 'joao@gmail.com', password: '123456') login_as(user, scope: :user) visit root_path click_on 'Filiais' click_on 'Registrar uma nova filial' fill_in 'Nome', with: 'Campus code' fill_in 'CNPJ', with: '63.463.524/0001-39' fill_in 'Endereço', with: 'Av. Paulista, 88' click_on 'Enviar' expect(current_path).to eq subsidiary_path(Subsidiary.last) expect(page).to have_content('Campus code') expect(page).to have_content('63.463.524/0001-39') expect(page).to have_content('Av. Paulista, 88') expect(page).to have_link('Voltar') end end
require 'rails_helper' describe ProjectsController do let(:admin) { create_user2(admin: true) } let(:non_member) { create_user2 } let(:project) { create_project } let(:member) {create_user2} describe 'GET #index' do describe 'Permissions' do it 'should redirect a visitor to sign in path' do get :index expect(response).to redirect_to sign_in_path end it 'should render projects page for a logged in user ' do user = create_user session[:user_id] = user.id get :index expect(response).to render_template :index end end end describe 'GET #show' do it 'should redirect a visotor to sign in path' do project = create_project get :show, id: project.id expect(response).to redirect_to sign_in_path end it 'should redirect a non member to projects path' do project = create_project user = create_user2 session[:user_id] = user.id membership = create_membership(project, create_user, role: 'Member') get :show, id: project.id expect(response).to redirect_to projects_path end # it 'should render the show for a member' do # membership = create_membership(project, member) # session[:user_id] = member.id # # get :show, id: project.id # # expect(response).to render_template :show # end end describe 'PATCH #update' do it 'should redirect a vistor to sign in path' do patch :update, id: project.id expect(response).to redirect_to sign_in_path end it 'it redirects a member to projects path' do membership = create_membership(project, member) end end describe 'DELETE #destroy' do it 'should not allow a non member to destroy' do session[:user_id] = member.id delete :destroy, id: project.id expect(response).to redirect_to projects_path expect(flash[:warning]).to eq("You do not have access to that project") end end end
class AddPhysicalCollectionUrlToCollections < ActiveRecord::Migration def change add_column :collections, :physical_collection_url, :string end end
# encoding: utf-8 require 'date' require 'i18n' require 'spec_helper' require File.join(File.dirname(__FILE__),'../lib/dt_helper') require File.join(File.dirname(__FILE__),'../lib/keventer_event') require File.join(File.dirname(__FILE__),'../lib/keventer_event_type') describe DTHelper do before(:each) do I18n.enforce_available_locales = true I18n.load_path += Dir[File.join(File.dirname(__FILE__), '../locales', '*.yml').to_s] @some_events = Array.new an_event = KeventerEvent.new an_event.event_type = KeventerEventType.new an_event.date = Date.parse("2012-12-04") an_event.id = 14 an_event.event_type.name = "Análisis, Estimación y Planificación con Scrum (Día 2 - CSD Track)" an_event.country = "Argentina" an_event.country_code = "AR" an_event.city = "Buenos Aires" an_event.is_sold_out = true an_event.registration_link = "https://eventioz.com.ar/retrospectivas-9-ene-2012/registrations/new" @some_events << an_event end it "should return a certain string for a sold out event" do expect(DTHelper::to_dt_event_array_json(@some_events)).to include("Completo") expect(DTHelper::to_dt_event_array_json(@some_events, false)).to include("Completo") end it "should return a certain string for a still valid event" do @some_events[0].is_sold_out = false @some_events[0].registration_link = "https://eventioz.com.ar/retrospectivas-9-ene-2012/registrations/new" expect(DTHelper::to_dt_event_array_json(@some_events)).not_to include("Completo") expect(DTHelper::to_dt_event_array_json(@some_events, false)).not_to include("Completo") end it "should return an empty json array when no event exist" do rsl = DTHelper::to_dt_event_array_json([], false, "comunidad", I18n) expect(rsl).to eq '{ "data": []}' end it "should take out diacritic(acute)" do expect(DTHelper::url_sanitize("áéíóúÁÉÍÓÚ")).to eq "aeiouAEIOU" end it "should add a title (from event type subtitle) to the event link" do @some_events[0].event_type.subtitle = "Some subtitle" expect(DTHelper::to_dt_event_array_json(@some_events)).to include('title=\"Some subtitle\"') end end
class ProductPromptsAddBackFillWeight < ActiveRecord::Migration def self.up add_column :product_prompts, :back_fill_weight, :integer, :null => false, :default => 0 end def self.down remove_column :product_prompts, :back_fill_weight end end
module ControllerScopeParameterInjection %i{get post patch put delete}.each do |meth| define_method meth do |*args, &block| if defined?(resource_owner_class_name) if args.last.is_a?(Hash) unless args.last.has_key?(:resource_owner_class_name) args.last[:resource_owner_class_name] = resource_owner_class_name end else args.push(resource_owner_class_name: resource_owner_class_name) end end super *args, &block end end end RSpec.shared_context :resource_owner_class_name, type: :controller do let(:resource_owner_class_name) { 'Rockauth::User' } end RSpec.configure do |config| config.include ControllerScopeParameterInjection, type: :controller end
require 'benchmark' require 'fileutils' require 'health_checks/checks/memory_check' require 'health_checks/checks/mongoid_check' require 'health_checks/checks/redis_check' module HealthChecks module_function def sidekiq(config, mongo_databases, redis_configs, sleep_seconds: 10) config.on(:startup) do LivenessCheckThread.new.start(mongo_databases, redis_configs, sleep_seconds) end end private class LivenessCheckThread STATUS_FILE = '/tmp/sidekiq_ok' def start(mongo_databases, redis_configs, sleep_seconds) logger = Sidekiq::Logging.logger logger.info "Starting liveness thread with #{sleep_seconds} sleep delay" checks = mongo_databases.map { |db| Checks::MongoidCheck.new(db) } checks += redis_configs.map{ |config| Checks::RedisCheck.new(config) } checks << Checks::MemoryCheck.new Thread.new do loop do elapsed_time = 0 failed = false checks.each do |check| elapsed_time = Benchmark.measure { check.run } logger.info "Time elapsed for #{check} was #{elapsed_time}" rescue => e logger.error e logger.info "Time elapsed for #{check} was #{elapsed_time}" failed = true break end handle_success unless failed sleep sleep_seconds end end end def handle_success FileUtils.touch(STATUS_FILE) end end end
class ReviewsController < ApplicationController before_action :set_rental before_action :authenticate_user!, only:[:create, :destroy] def create @review = @rental.reviews.new(review_params) @review.user = current_user @review.save redirect_back(fallback_location: root_path) end def destroy @review = @rental.reviews.find(params[:id]) @review_id = @review.id @review.destroy end private def review_params params.require(:review).permit(:message, :score, :rental_id) end def set_rental @rental = Rental.find(params[:rental_id]) end end
class ApplicationController < ActionController::Base before_action :move_to_root_path, except: [:create, :destroy, :update], if: :devise_controller? protected def move_to_root_path redirect_to root_path end end
require 'test_helper' class TeamTest < ActiveSupport::TestCase should have_many :season_teams should have_many :seasons should validate_uniqueness_of :name should validate_uniqueness_of :abbreviation end
class RootController < ApplicationController # ログイン画面(ユーザーはサインインしていない場合) # ユーザー画面(ユーザーはサインイン済の場合) def index # 利用規約承認画面から来た場合にユーザー情報の更新 if params[:approve] == 'true' current_user.approved_terms = true current_user.approved_terms_at = Time.now current_user.save end return unless logged_in? # ユーザーの所属組織のリストと # ユーザーと共同者のレポジトリのリストをGithubから取得する github = Github.new(oauth_token: current_user.access_token) @username = github.users.get(id: current_user.github_id).login @collaborators = [] @orgs = [] @repos = [] user_orgs_list = github.orgs.list user_repos_list = github.repos.list # 協力者の名前のリストの生成 user_repos_list.each do |repo| next if repo.owner.login == @username next if @collaborators.include?(repo.owner.login) @collaborators << repo.owner.login end # 所属組織の名前のリストの生成 user_orgs_list.each { |org| @orgs << org.login } # レポジトリの情報(名前、所有者、issueの有無)のリストの生成 user_repos_list.each do |repo| add_repo(repo) if repo.owner.login == @username end user_repos_list.each do |repo| add_repo(repo) unless repo.owner.login == @username end @orgs.each do |org| org_repos_list = github.repos.list(org: org) org_repos_list.each do |repo| add_repo(repo) end end render 'userpage' end private # レポジトリの情報のリストに追加 def add_repo(repo) name = repo.name owner = repo.owner.login has_issue = repo.has_issues @repos << Repository.new(name, owner, has_issue) end end
require 'json' module Stax module DynamoDB ## monkey-patch this method to apply any app-specific changes to payload ## args: logical_id, payload hash ## returns: new payload def dynamo_local_payload_hacks(id, payload) payload end end module Cmd class DynamoDB < SubCommand no_commands do ## client for dynamodb-local endpoint on given port def client(port) @_client ||= ::Aws::DynamoDB::Client.new(endpoint: "http://localhost:#{port}") end ## get CFN template and return hash of table configs def dynamo_local_tables JSON.parse(my.cfn_template).fetch('Resources', {}).select do |_, v| v['Type'] == 'AWS::DynamoDB::Table' end end ## convert some CFN properties to their SDK equivalents def dynamo_payload_from_template(id, template) template['Properties'].tap do |p| p['TableName'] ||= id # use logical id if no name in template p['StreamSpecification']&.merge!( 'StreamEnabled' => true ) p['SSESpecification'] &&= { 'Enabled' => p.dig('SSESpecification', 'SSEEnabled') } p.delete('TimeToLiveSpecification') p.delete('Tags') end end ## convert property names to ruby SDK form def dynamo_ruby_payload(payload) payload&.deep_transform_keys do |key| key.to_s.underscore.to_sym end end ## create table def dynamo_local_create(payload, port) client(port).create_table(dynamo_ruby_payload(payload)) rescue ::Aws::DynamoDB::Errors::ResourceInUseException => e warn(e.message) # table exists rescue Seahorse::Client::NetworkingError => e warn(e.message) # dynamodb-local probably not running end end desc 'local-create', 'create local tables from template' method_option :tables, aliases: '-t', type: :array, default: nil, desc: 'filter table ids' method_option :payload, aliases: '-p', type: :boolean, default: false, desc: 'just output payload' method_option :port, aliases: '-P', type: :numeric, default: 8000, desc: 'local dynamo port' def local_create tables = dynamo_local_tables tables.slice!(*options[:tables]) if options[:tables] tables.each do |id, value| payload = dynamo_payload_from_template(id, value) payload = my.dynamo_local_payload_hacks(id, payload) # apply user-supplied hacks if options[:payload] puts JSON.pretty_generate(payload) else puts "create table #{id}" dynamo_local_create(payload, options[:port]) end end end desc 'local-delete', 'delete local tables from template' method_option :tables, aliases: '-t', type: :array, default: nil, desc: 'filter table ids' method_option :port, aliases: '-P', type: :numeric, default: 8000, desc: 'local dynamo port' def local_delete tables = dynamo_local_tables tables.slice!(*options[:tables]) if options[:tables] tables.each do |id,_value| puts "deleting table #{id}" client(options[:port]).delete_table(table_name: id) end end end end end
require "./csv_to_email" # configuring settings below for spec/support/names.csv # # run with: # ruby driver.rb spec/support/names.csv # CsvToEmail.configure do |config| config.email_domain = 'example.com' # config.max_email_length = 8 # config.default_max_lastname_length = config.max_email_length - 1 config.csv_lastname_field_num = 1 config.csv_firstname_field_num = 2 end def run unless ARGV.count == 1 and File.exist? ARGV[0] print_usage and exit end filename = ARGV[0] processor = CsvToEmail::Processor.new filename processor.populate_people_from_file processor.show_people end def print_usage puts "Usage: ruby #{__FILE__} input_file.csv" exit end run
require_relative "../require/macfuse" class ArchivemountMac < Formula desc "File system for accessing archives using libarchive" homepage "https://www.cybernoia.de/software/archivemount.html" url "https://www.cybernoia.de/software/archivemount/archivemount-0.9.1.tar.gz" sha256 "c529b981cacb19541b48ddafdafb2ede47a40fcaf16c677c1e2cd198b159c5b3" bottle do root_url "https://github.com/gromgit/homebrew-fuse/releases/download/archivemount-mac-0.9.1" sha256 cellar: :any, big_sur: "84dfb26c79c5d3cd6596bbbbb1398dd7d0a855eab32ff2b1192cd36235c34ab9" sha256 cellar: :any, catalina: "0d838c1b6684201cf9ff7bcc1120052bfce87c31950622961852a9e17243cd94" sha256 cellar: :any, mojave: "42170c737f1fd151a4e36276c6929fe49aa69137886238ec38f04a84c123f26b" end depends_on "pkg-config" => :build depends_on "libarchive" depends_on MacfuseRequirement depends_on :macos def install setup_fuse ENV.append_to_cflags "-I/usr/local/include/osxfuse" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do system bin/"archivemount", "--version" end end
class Application < ApplicationRecord validates_presence_of :name_of_user, :address, :status belongs_to :user has_many :pet_applications has_many :pets, through: :pet_applications end
require 'line' describe Line do it '#evalutate_line returns empty string for 0,0,*' do expect(Line.evalutate_line(0,0,'A')).to eq "" expect(Line.evalutate_line(0,0,'B')).to eq "" end it '#evaluate_line returns A for 1,1,A' do expect(Line.evalutate_line(1,1,'A')).to eq("A") expect(Line.evalutate_line(1,1,'B')).to eq("B") end it '#evaluate_line returns _A_ for 2,1,A' do expect(Line.evalutate_line(2,1,'A')).to eq(" A ") end it '#evaluate_line returns C_C for 2,2,C' do expect(Line.evalutate_line(2,2,'C')).to eq("C C") end it '#evaluate_line returns C___C for 3,3,C' do expect(Line.evalutate_line(3,3,'C')).to eq("C C") end it '#evaluate_line returns _C_C_ for 3,2,C' do expect(Line.evalutate_line(3,2,'C')).to eq(" C C ") end it '#outer_space returns _ for 3,2,C' do expect(Line.outer_space(3, 2)).to eq(" ") end 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_one :about_content has_one :business_detail has_one :integration has_one :services_content has_one :extra_page has_one :upload has_many :visits, class_name: "Ahoy::Visit" after_create :create_about_content, :create_business_detail, :create_integration, :create_services_content, :create_extra_page, :create_upload, :new_user_email def create_about_content about_content = AboutContent.new about_content.user_id = self.id about_content.save! end def create_business_detail business_detail = BusinessDetail.new business_detail.user_id = self.id business_detail.save! end def create_integration integration = Integration.new integration.user_id = self.id integration.save! end def create_services_content services_content = ServicesContent.new services_content.user_id = self.id services_content.save! end def create_extra_page extra_page = ExtraPage.new extra_page.is_complete = true extra_page.user_id = self.id extra_page.save! end def create_upload upload = Upload.new upload.user_id = self.id upload.save! end def new_user_email UserMailer.send_admin_user_details(self.id).deliver_later end end
def integral f, start, stop, step_size=0.001 t = lambda do |h| trapezoidal_integral(f, start, stop, h) end return richardson_extrapolation(t, 2, step_size, 2) end # f - Function to extrapolate from # n - Targeted function's rate of convergence # h - Step size # t - Scaling def richardson_extrapolation f, n, h, t return ((t**n) * f.call(h/t) - f.call(h)) / (t**n - 1) end def trapezoidal_integral f, start, stop, inc result = 0 (start..stop).step(inc).each_cons(2) do |i, j| area = (j - i) * (f.call(i) + f.call(j)) / 2 result += area if !area.nan? and !area.infinite? end return result end # f - Function to query # x1 - Starting point 1 # x2 - Starting point 2 # y - y position that is searched for def secant_method f, x1, x2, y=0, timeout=30 g = lambda { |x| f.call(x) - y } l = [x1, x2] lf1 = g.call(l[-1]).to_f lf2 = g.call(l[-2]).to_f while l.size == l.uniq.size and (l[-1] - l[-2]).abs > 10**(-7) and l.size() < timeout and lf1 != lf2 l.push(l[-1] - lf1*(l[-1] - l[-2])/(lf1 - lf2)) lf2 = lf1 lf1 = g.call(l[-1]) end return l[-1] end
class ProductController < ApplicationController include Pricing include StorePages layout proc { |controller| case controller.action_name when *%w(show show_by_tag) then "product" when *%w(new create index) then "application" when *%w(details offers) then "browse" end } before_filter :check_for_add_product_enabled, :only => [:new, :create] before_filter :check_show_new, :only => [:show] before_filter :setup_from_id, :only => [:show_by_tag, :show, :details, :show_all_tags, :show_all_i_am_tags] before_filter :display_category_sub_tabs, :only => [:show, :list] uses_viewpoints_tiny_mce :only => [:show] DEFAULT_PRODUCTS_PER_PAGE = 10 def index set_review_it_mode if params[:review_it] == true @display_site_down = true @taxonomy = DisplayTaxonomyItem.find_add_a_product_root # set up site catalyst params @web_analytics.page_stack = ['Write a Review', 'Add a Product', 'Category Selection', 'Index'] @web_analytics.page_type = 'Write a Review' end # This is a legacy action that used to paginate SDC products within a given category. # We no longer do this, so redirect the user to the main category page. In fact, as of # now, only bots remember these old urls, users aren't finding them, since we don't link # to them def list category = Category.find_by_param params[:category_path].last unless params[:category_path].blank? unless category return handle_resource_not_found(BrowseController::MISSING_CATEGORY_MESSAGE) end permanent_redirect_to url_for(:controller => "navigation", :action => "index", :id => category.to_param) end # Supports filtering product reviews by a specific pro or con. This is natively # supported in the show function if you know the n-value ahead of time. In this case # we're simply providing a pretty url (pros/cons) and handling lookup of an n-value # from an actual text-based value. def show_by_tag if params[:tag_value] and params[:tag_type] if value = (nt = NormalizedTag.find(params[:tag_value].match(/.*-(\d+)$/).captures.first)).value if dim_value = Endeca::DimensionSearchQuery.dim_value_for(params[:tag_type], nt.normalized, true) params['N'] = [dim_value] end end end show render :template => '/product/show' end # Show products based on a partner key # Primarily used to allow cobrand clients to construct links to the community site # Will automatically redirect to permalink # Allow URLS like # http://viewpoints.dev/products/pk/2004271661 # http://viewpoints.dev/products/pk/:id def show_by_partner_key p = PartnerProduct.find_by_partner_key(params[:id], :include => :product) @product = p.product show end def show return handle_resource_not_found("Product does not exist") unless @product && (@product.status == :active || @product.num_reviews > 0) unless @product.new_record? || @product.to_param == params[:id] params[:id] = @product.to_param return permanent_redirect_to(product_url(params.except(:action))) end # Removing the Rack::Cache for the show method because it is interacting with the # Rails page_cache in odd ways. Eventually we want to move completely to Rack::Cache # but for the time being we are going to go with the status quo and use the page_cache. # last_modified = [@product.updated_at, @product.stat.updated_at].compact.max # last_modified = last_modified.utc unless last_modified.nil? # return unless stale?(:etag => [@cobrand, last_modified, @product.stat], :last_modified => last_modified, :public => cache_control_public?) # In the meantime, aping page caching behavior but using Rack-Cache: expires_in 30.minutes, :public => cache_control_public? if cacheable? if @product.redirect_to_only_review? && params[:b].nil? redirect_to review_path(@product.reviews.active.first) return end @rating_just_saved = params[:rating_just_saved] == 'true' @category_trail = @product.category.primary_trail @category = @product.category @tab = (params[:tab].blank? ? nil : params[:tab].to_sym) @nav_state = ProductNavState.new params @nav_state[:product] = @product @nav_state[:per_page] = cookies['navsize'] @endeca_req = Endeca::Request.new @nav_state.endeca_opts @endeca_res = @endeca_req.execute @user_reviews = Review.from_endeca_response @endeca_res, :include=>[ :source, :product, {:user=>[{:badgings=>:badge} ,:user_stat, :primary_photo_association]}, :stat, :i_ams ] track_reviews @user_reviews no_crumbs = @endeca_res.breadcrumb_hash['Star Rating'].blank? && @endeca_res.breadcrumb_hash['Pros'].blank? && @endeca_res.breadcrumb_hash['Cons'].blank? no_page = @nav_state[:page].to_i == 1 no_sort = @nav_state[:sort].blank? @show_landing_only_elements = no_crumbs && no_page && no_sort if @show_landing_only_elements && @product.stat.most_helpful_pro_review_id && @product.stat.most_helpful_con_review_id @most_helpful_pro_review = @user_reviews.detect { |r| r.id == @product.stat.most_helpful_pro_review_id } @most_helpful_pro_review ||= @product.stat.most_helpful_pro_review @most_helpful_con_review = @user_reviews.detect { |r| r.id == @product.stat.most_helpful_con_review_id } @most_helpful_con_review ||= @product.stat.most_helpful_con_review if @most_helpful_pro_review.active? && @most_helpful_con_review.active? @user_reviews.reject! { |r| r.id == @most_helpful_pro_review.id } @user_reviews.reject! { |r| r.id == @most_helpful_con_review.id } else @most_helpful_pro_review = @most_helpful_con_review = nil end end @paginator = Paginator.new self, @endeca_res.metainfo.total_number_of_matching_records.to_i, @endeca_res.metainfo.number_of_records_per_page.to_i, @nav_state[:page].to_i # OPTIMIZE: Should this be called every #show? Product.fetch_sdc_info_if_no_attr_details(@product) if params[:source_id] && params[:source_key] @meta_noindex = @meta_nofollow = true elsif @product.stat.active_review_count < 2 @meta_noindex = true @meta_nofollow = false else @meta_noindex, @meta_nofollow = @nav_state.meta_robots end @vibrant_media_ipid = @product.category.find_top_level.vibrant_media_product_ipid @web_analytics.tab = @tab @web_analytics.product = @product @web_analytics.page_number = @nav_state[:page] if @tab == :prices # product page with param 'tab' = 'prices' offer_opts = { :num_offers => 15, :omit_amazon => @product.mapped_to_amazon?, :page_type => 'prices_tab' } offer_opts[:zip_code] = session_user.zip_code if session_user @min_price, @max_price, @total_store_offers, @sdc_logo, @store_offers = find_sdc_product_offers( @product, offer_opts) redirect_to url_for(:action => 'show', :id => @product) if @total_store_offers == 0 return end if params[:N] trans_n = @web_analytics.breadcrumbs_to_text(@endeca_res.breadcrumbs) @web_analytics.facet_nav(trans_n,session[:last_n_value_prod],nil) session[:last_n_value_prod] = trans_n else # no N, clear the session session[:last_n_value_prod] = nil end # meta stuff sound_bite = @product.representative_review.sound_bite if @product.representative_review @meta_description = "Read #{@product.title} reviews and find out why people rate it #{@product.average_star_rating} out of #{"%1.2f" % Review::STARS_MAX_VALUE} stars. " @meta_description << "People say, '#{sound_bite}'. " if sound_bite @meta_keywords = "review, reviews, consumer, consumer reviews, #{@product.title}" # 625 summary and tag cloud # 300 per review # -100 for finesse # 100px + 75 * store offers up to 5 if sdc center_col_pixels = 525 + 300 * @user_reviews.size center_col_pixels += 150 + 60 * @store_offers.size if @store_offers @left_rail_ad_pixels = center_col_pixels - 425 @right_rail_ad_pixels = center_col_pixels + 800 # -200px for star ratings chart @right_rail_ad_pixels -= 100 + 5 * @store_offers.size if @store_offers if params[:wants] == 'rss' @reviews = @user_reviews @title = "Latest reviews about #{@product.title}" render :template => 'common/rss', :layout => false end # Store pages specific logic if App.store_pages[:enabled] and is_store? @product @news_page = params[:news_page] || 1 @events_page = params[:events_page] || 1 @news_page_size = App.store_pages[:news_page_size] @events_page_size = App.store_pages[:events_page_size] @store_tab = params[:store_tab] || 'events' if @store_tab == 'news' @news_page, @article_id = find_page_for_article(@cobrand, @product, 'news', params[:article_id], @news_page_size, @news_page) elsif @store_tab == 'events' @events_page, @article_id = find_page_for_article(@cobrand, @product, 'events', params[:article_id], @events_page_size, @events_page) end @total_news_count, @news = news_articles(@cobrand, @product, @news_page, @news_page_size) @total_events_count, @events = events_articles(@cobrand, @product, @events_page, @events_page_size) render 'mystore/store_page', :layout => 'layouts/store_page' end end def show_all_i_am_tags return handle_resource_not_found("Product does not exist") unless @product && (@product.status == :active || @product.num_reviews > 0) unless @product.new_record? || @product.to_param == params[:id] # XXX FIXME AJA - what to do? params[:id] = @product.to_param return permanent_redirect_to(product_url(params)) end @category_trail = @product.category.primary_trail @nav_state = ProductNavState.new params @nav_state[:product] = @product @nav_state[:per_page] = 1 @dim_name = params[:dim_name] @endeca_req = Endeca::Request.new @nav_state.endeca_opts @endeca_res = @endeca_req.execute @web_analytics.product = @product # TODO LTC not sure this goes across b/c the partial page update @web_analytics.page_name += ": Show All I Am Tags" render :update do |page| page.replace_html "product_#{@dim_name}_tags_div", :partial => 'wdycw', :locals => { :endeca_res => @endeca_res, :dimension_name => @dim_name, :product => @product, :nav_state => @nav_state, :max_visible_values => 100} end end def show_all_tags return handle_resource_not_found("Product does not exist") unless @product && (@product.status == :active || @product.num_reviews > 0) unless @product.new_record? || @product.to_param == params[:id] # XXX FIXME AJA - what to do? params[:id] = @product.to_param return permanent_redirect_to(product_url(params)) end @category_trail = @product.category.primary_trail @nav_state = ProductNavState.new params @nav_state[:product] = @product @nav_state[:per_page] = 1 @dim_name = params[:dim_name] @endeca_req = Endeca::Request.new @nav_state.endeca_opts @endeca_res = @endeca_req.execute @web_analytics.product = @product # TODO LTC not sure this goes across b/c the partial page update @web_analytics.page_name += ": Show All #{@dim_name} Tags" render :update do |page| page.replace_html "product_#{@dim_name}_tags_div", :partial => 'show_all_tags' end end def details return handle_resource_not_found unless @product @category_trail = @product.category.primary_trail unless @sdc_logo begin @sdc_logo = @product.load_partner_details rescue logger.error "Unable to load details: #{$!}" end end @meta_noindex = @meta_nofollow = true @web_analytics.product = @product @web_analytics.display_mode = "details" render :update do |page| page.replace_html "details_tab_sheet", :partial => "details" end end # offers expects params[:id] to be the Product.id (numeric). It just redirects to # the product page since we no longer have a separate page for offers def offers @product = Product.find_by_id params[:id] return handle_resource_not_found('Product not found') unless @product permanent_redirect_to product_url(:id => @product) end def new @display_site_down = true @category = Category.find(params[:category_id]) @product_descriptors = @category.product_questions.active.descriptor_kind.find(:all, :order => 'position') @product_attributes = @category.product_questions.active.attribute_kind.find(:all, :order => 'position') @web_analytics.page_stack = ['Write a Review', 'Add a Product', 'Add a Product Form'] @web_analytics.page_type = 'Write a Review' end def create @display_site_down = true category_id = params[:category_id] @category = Category.find(category_id) answers_hash = params[:answers] || {} begin @product = Product.find_or_create_from_answers_hash(@category, answers_hash, session_user) # if there are errors, send em back to the new form if @product.errors.size > 0 logger.debug "Errors creating product #{@product.errors.inspect}" if logger.debug? @product_descriptors = @category.product_questions.active.descriptor_kind.find(:all, :order => 'position') @product_attributes = @category.product_questions.active.attribute_kind.find(:all, :order => 'position') @web_analytics.page_stack = ['Write a Review', 'Add a Product', 'Add a Product Form with Errors'] @web_analytics.page_type = 'Write a Review' render :update do |page| page.replace_html :error_messages_div, :partial => 'new_errors' page << 'Element.scrollTo(\'error_messages_div\')' page << "event_track(#{"'#{@web_analytics.google_analytics_url}'"})" end return end @product.product_answers.each do |answer| (session[:unauthenticated_product_answers] ||= []) << answer.id unless answer.user end render :update do |page| page.redirect_to new_review_url(:product_id => @product.id) end rescue => ex logger.fatal "Exception when adding a product.\n#{ex}\n#{ex.backtrace.join "\n"}" render :update do |page| page.replace_html :error_messages_div, :partial => 'new_errors' page.replace_html :buttons_p, :partial => 'continue_button' page << 'Element.scrollTo(\'error_messages_div\')' end end end def load_where_to_buy return render(:nothing => true) if params[:id].blank? @product = Product.find_by_param(params[:id]) return render(:nothing => true) if @product.blank? || !monetizable_product?(@product) offer_opts = { :num_offers => 3, :omit_amazon => @product.mapped_to_amazon?, :page_type => (params[:type] == 'p' ? 'product' : 'review') } offer_opts[:zip_code] = session_user.zip_code if session_user @min_price, @max_price, @total_store_offers, @sdc_logo, @store_offers = find_sdc_product_offers( @product, offer_opts) render :update do |page| if @store_offers.blank? logger.debug "ProductController: no store offers" # No offers found but we are in a "productized" category # ...see if the cobrand allows "search for it on PARTNER" widgets if App.pricing['find_on_sdc'] logger.debug "ProductController: adding search on sdc" linkin_id = params[:type] == 'p' ? App.sdc_tracking_ids['link_unit_pro'] : App.sdc_tracking_ids['link_unit_rev'] page.insert_html :bottom, :where_to_buy, :partial => 'search_for_it', :locals => { :product => @product, :site => "sdc", :site_text => "Shopping.com", :site_url => sdc_keyword_search_url(@product, linkin_id) } end if App.pricing['find_on_ebay'] logger.debug "ProductController: adding search on ebay" customid = params[:type] == 'p' ? 'product' : 'review' page.insert_html :bottom, :where_to_buy, :partial => 'search_for_it', :locals => { :product => @product, :site => "ebay", :site_text => "eBay.com", :site_url => ebay_keyword_search_url(@product, customid) } end else logger.debug "ProductController: have store offers" if App.pricing['wtb_widgets_enabled'] logger.debug "ProductController: adding mini where to buy" page << "if($('where_to_buy_mini')){" page.replace_html :where_to_buy_mini, :partial => 'common/where_to_buy_mini', :locals => { :product => @product, :min_price => @min_price, :total_store_offers => @total_store_offers} page << "}" logger.debug "ProductController: adding normal where to buy" page << "if($('where_to_buy')){" page.replace_html :where_to_buy, :partial => 'common/where_to_buy', :object => @store_offers, :locals => { :total_store_offers => @total_store_offers} page << "}" end if App.pricing['product_page_tab_enabled'] logger.debug "ProductController: prices tab" page << "if ($('prices_tab')) $('prices_tab').show();" page << "if ($('prices_tab_sheet')) {} else {" page.replace_html :prices_tab, "#{link_to "Compare Prices", product_path(@product.to_param, :tab => 'prices')}" page << "}" end end if App.pricing['wtb_widgets_enabled'] logger.debug "ProductController: adding summary pricing" # AJA TODO: this widget is always hidden show.rhtml by parent div page << "if($('summary_pricing')){" page.replace_html :summary_pricing, :partial => 'product/summary_pricing', :locals => { :id => params[:id], :store_offers => @store_offers, :min_price => @min_price, :max_price => @max_price } page << "}" end end end def rss end private def covary_hash_answer(hash, question) return '' if hash.blank? || hash[question.id.to_s].blank? answer = hash[question.id.to_s] case question.presentation_type when :select answer = '' if answer == SELECT_DEFAULT_ITEM_SELECT_TEXT || answer.blank? when :textfield, :checkbox answer = '' if answer.blank? else raise "unsupported presentation type: #{question.presentation_type}" end answer end # this before_filter ensures that any requests for sdc unreviewed product pages get # redirected to the canonical URL for those pages def check_show_new return true unless params[:source_id] && params[:source_key] return true if request.request_uri =~ /\/product\/show_new/ permanent_redirect_to params false end def setup_from_id if params[:id] @product = Product.find_by_param params[:id], :include => :stat return unless @product elsif params[:source_id].to_i == Source["sdc"].id data = Sdc3::GeneralSearch.execute :trackingId => App.sdc_tracking_ids['default'], :productId => params[:source_key] products = PartnerProduct.save_from_sdc_to_db data, Category.find(params[:category_id]) @product = products.first end end private def cacheable? return false if session_user || params[:N] || params[:page] || params[:sort] || params[:min_rating] || cookies[:navsize] || params[:tab] true end def create_answer(question, answer_value) if answer_value.is_a? Array array_answer = [] answer_value.each do |av| av.strip! unless av.nil? unless av.blank? && question.descriptor? answer = ProductAnswer.new answer.question = question answer.user = session_user answer.value = av descriptor_answers << answer end end return array_answer else answer = create_answer_from_string(q, answer_value) end end def create_answer_from_string(question, answer_value) answer_value.strip! unless answer_value.nil? answer = ProductAnswer.new :question => question, :user => session_user, :value => answer_value end def canonical_link super.sub(/[\?\#].*$/) {} end def check_for_add_product_enabled if !App.config['show_add_product_link?'] respond_to do |format| format.html { render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 } format.js { render :update, :status => 404 do |page| page.redirect_to("/404.html") end } end return false end return true end end
class AddCompetitionIdToEntry < ActiveRecord::Migration def change change_table :entries do |t| t.integer :competition_id t.index :competition_id end end end
# frozen_string_literal: true class Practice < ApplicationRecord module Status CANCELED = 'CANCELED' HOLIDAY = 'HOLIDAY' LOCKED = 'LOCKED' end STATUS_CLASSES = { Status::CANCELED => 'danger', Status::HOLIDAY => 'success', Status::LOCKED => 'info', }.freeze belongs_to :group_schedule belongs_to :instructor, class_name: :User, optional: true has_many :attendances, dependent: :destroy scope :after, ->(limit) { from_date = limit.to_date includes(:group_schedule).references(:group_schedules) .where('year > :year OR (year = :year AND week > :week) OR ' \ '(year = :year AND week = :week AND group_schedules.weekday > :wday)', year: from_date.cwyear, week: from_date.cweek, wday: from_date.cwday) } validates :group_schedule_id, uniqueness: { scope: %i[year week] } def self.status_options(blank = nil) [[blank, nil]] + Status.constants.map { |c| [status_str(c), c] } end def self.status_str(status) return if status.blank? I18n.t(status.downcase) end def status_class STATUS_CLASSES[status] end def group_semester GroupSemester.where(group_id: group_schedule.group_id) .find_by('first_session <= :date AND last_session >= :date', date: date) || GroupSemester.where(group_id: group_schedule.group_id).includes(:semester).references(:semesters) .find_by('semesters.start_on <= :date AND semesters.end_on >= :date', date: date) end def date return unless group_schedule Date.commercial(year, week, group_schedule.weekday) end def start_at date.at(group_schedule.start_at) end def end_at date.at(group_schedule.end_at) end def imminent? Time.current > (start_at - 30.minutes) end def passed? Time.current > end_at end def canceled? status == Status::CANCELED end def holiday? status == Status::HOLIDAY end def locked? status == Status::LOCKED end def movable? !immovable? end def immovable? status.present? end def title "Trening #{to_s(date: false, time: false)}#{" #{status_str}" if status}" end def body instructor? ? '' : nil end def to_s(group: true, weekday: false, date: true, time: true) week_day = " #{ApplicationController.helpers.day_name(self.date.wday)}" if weekday group_name = group_schedule.group.full_name if group "#{group_name}#{week_day} #{self.date if date}#{" #{group_schedule.start_at.to_s(false)}" if time}" end def attendance_for(user) attendances.find { |a| a.user_id == user.id } || attendances.build(user: user) end delegate :instructor?, to: :group_schedule def status_str self.class.status_str(status) end end
require('capybara/rspec') require('./app') require('pry') Capybara.app = Sinatra::Application set(:show_exceptions, false) describe('Word path', {:type => :feature}) do it('will visit the index page and follow link to /add_word page') do visit('/') click_link('Add Word to Dictionary') expect(page).to have_content("Add a Word to the Dictionary") end it('will fill in the add-word form and then take user to success page') do visit('/add_word') fill_in('term', :with => 'Ruby') click_button('Submit') expect(page).to have_content("Dictionary") 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) unless User.any? User.create(first_name: "Brock", last_name: "Sauvage", email: "brocksauvage@gmail.com", password: "test") end unless Genre.any? [ "Ambient", "Anthem", "Bluegrass", "Blues", "Children", "Cinematic", "Classical", "Comedy", "Country", "Dance", "Disco", "Downtempo", "Drama", "Electronic", "Emotional", "Epic", "Ethereal", "Experimental", "Folk", "Funk", "Game Show", "Hip Hop", "Holiday", "Hopeful", "Indie", "Jazz", "Latin", "Lounge", "Metal", "Mnemonic", "Organic", "Polka", "Pop", "Punk", "Quirky", "R&B / Soul", "Religious", "Retro", "Rock", "Rock / Pop", "Soft Rock", "Soul", "Soundscape", "Sports", "Surf", "Unknown", "Western", "World" ].each do |genre| Genre.find_or_create_by(name: genre) end end unless Mood.any? [ "Adventurous", "Aggressive", "Ambient", "Bizarre", "Bright", "Calm", "Carefree", "Cheerful", "Cheesy", "Chill", "Cinematic", "Classy", "Confident", "Contemplative", "Cool", "Cute", "Dark", "Determined", "Dirty", "Dramatic", "Dreamy", "Driving", "Eclectic", "Eerie", "Elegant", "Emotional", "Energetic", "Epic", "Ethereal", "Exciting", "Experimental", "Festive", "Fun", "Gentle", "Goofy", "Grandiose", "Gritty", "Happy", "Heavy", "Honest", "Hopeful", "Inspirational", "Inspiring", "Intense", "Intimate", "Introspective", "Laid Back", "Light", "Lonely", "Magical", "Melancholy", "Minimal", "Mnemonic", "Moody", "Motivating", "Moving", "Mysterious", "Nostalgic", "Optimistic", "Organic", "Peaceful", "Playful", "Positive", "Powerful", "Quirky", "Rebellious", "Reflective", "Relaxed", "Retro", "Romantic", "Rugged", "Sad", "Sassy", "Satisfied", "Scary", "Sentimental", "Serious", "Sexy", "Sleazy", "Somber", "Spacious", "Spiritual", "Strange", "Suspenseful", "Tense", "Tough", "Upbeat", "Uplifting", "Vintage", "Whimsical", "Youthful" ].each do |mood| Mood.find_or_create_by(name: mood) end end
Spree::Admin::ProductPropertiesController.class_eval do skip_before_filter :find_properties skip_before_filter :setup_property def index categories = @product.sorted_property_categories @data = categories.map do |cat| properties = cat.product_properties.where(product_id: @product.id) properties.map! do |property| { key: property.property_name, value: property.value, display: property.display?, measurement: property.measurement_unit } end { name: cat.name, properties: properties } end uncategorized = @product.product_properties.uncategorized if uncategorized.any? uncategorized.map! do |property| { key: property.property_name, value: property.value, display: property.display?, measurement: property.measurement_unit } end @data.unshift({ name: nil, properties: uncategorized }) end @data = @data.to_json end end
class V2::QuestionsController < ApplicationController respond_to :json def show respond_with "sample data v2" end end
# frozen_string_literal: true source "https://rubygems.org" git_source(:github) { |repo| "https://github.com/#{repo}.git" } # this line is used by heroku and several CIs ruby "3.0.1" # only bundle the parts of Rails that are actually used # don't forget to update config/application.rb when you add a gem # to update the version run: `bundle update actionpack activemodel ... railties` as one command rails_version = "6.1.3" gem "actionpack", "~> #{rails_version}" gem "activemodel", "~> #{rails_version}" gem "activerecord", "~> #{rails_version}" gem "railties", "~> #{rails_version}" gem "pg", "~> 1.2" # postgresql db adapter gem "puma", "~> 5.0" # web server gem "rack-requestid", "~> 0.2" # set a request_id in the middleware gem "rack-timeout", "~> 0.6", require: "rack/timeout/base" # set a custom timeout in the middleware gem "sass-rails", ">= 6" # to use Sass / SCSS group :development, :test do gem "amazing_print" # nicer formatted console output gem "bundler-audit", "~> 0.6" # to ensure no used dependencies have know security warnings # gem "capybara", "~> 3.33" # acceptance test framework for system tests gem "rspec-rails", "~> 5.0" # rspec test framework gem "rubocop", "~> 1.14.0", require: false # code linter gem "rubocop-performance", "~> 1.11" # rubocop extension gem "rubocop-rails", "~> 2.10" # rubocop extension gem "rubocop-rake", "~> 0.5" # rubocop extension gem "rubocop-rspec", "~> 2.0" # rubocop extension end group :development do gem "listen", "~> 3.3" # reloads changed files end group :test do # gem "selenium-webdriver", "~> 3.142" # for headless browser tests # gem "webmock", "~> 3.9" # stub response to requests end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby]
require "goon_model_gen" module GoonModelGen module Golang class Type attr_reader :name attr_accessor :package # @param name [string] def initialize(name) @name = name end # @param pkgs [Packages] def resolve(pkgs) raise NotImplementedError, "#{self.type.name} doesn't implement resolve method" end # @param pkg2alias [Hash<String,String>] # @return [string] def qualified_name(pkg2alias = nil) if package && package.name pkg_name = (pkg2alias && package.path ? pkg2alias[package.path] : nil) || package.name "#{pkg_name}.#{name}" else name end end def memo @memo ||= {} end end end end
# frozen_string_literal: true # Copyright (c) 2008-16 Peter H. Boling of RailsBling.com # Released under the MIT license module SanitizeEmail # Tools for overriding addresses class OverriddenAddresses # Raised when after applying all sanitization rules there are no addresses to send the email to. class MissingTo < StandardError; end # Raised if there is a recipient type that sanitize_email doesn't recognize. # If you get this error please report it. # recognized recipient types are: TO, CC, and BCC class UnknownOverride < StandardError; end REPLACE_AT = [/@/, ' at '].freeze REPLACE_ALLIGATOR = [/[<>]/, '~'].freeze attr_accessor :overridden_to, :overridden_cc, :overridden_bcc, :good_list, # White-listed addresses will not be molested as to, cc, or bcc :bad_list, # Black-listed addresses will be removed from to, cc and bcc when sanitization is engaged :sanitized_to, :sanitized_cc, :sanitized_bcc # Replace non-white-listed addresses with these sanitized addresses. def initialize(message, **args) # Not using extract_options! because non-rails compatibility is a goal args = SanitizeEmail::Config.to_init.merge(args) @sanitized_to = args[:sanitized_to] @sanitized_cc = args[:sanitized_cc] @sanitized_bcc = args[:sanitized_bcc] @good_list = args[:good_list] || [] @bad_list = args[:bad_list] || [] @overridden_to = to_override(message.to) @overridden_cc = cc_override(message.cc) @overridden_bcc = bcc_override(message.bcc) end # Allow good listed email addresses, and then remove the bad listed addresses def good_listize(real_addresses) good_listed = clean_addresses(real_addresses, :good_list) good_listed = clean_addresses(good_listed, :bad_list) unless good_listed.empty? good_listed end def to_override(actual_addresses) to = override_email(:to, actual_addresses) raise MissingTo, "after overriding :to (#{actual_addresses}) there are no addresses to send in To: header." if to.empty? to.join(',') end def cc_override(actual_addresses) override_email(:cc, actual_addresses).join(',') end def bcc_override(actual_addresses) override_email(:bcc, actual_addresses).join(',') end def override_email(type, actual_addresses) # Normalized to an arrays # puts "override_email 1: #{type} - #{actual_addresses}" real_addresses = Array(actual_addresses) # puts "override_email 2: #{type} - #{real_addresses}" # If there were no original recipients, then we DO NOT override the nil with the sanitized recipients return [] if real_addresses.empty? good_listed = good_listize(real_addresses) # puts "override_email 3: #{type} - #{good_listed}" # If there are good_list addresses to send to then use them as is, no mods needed return good_listed unless good_listed.empty? # TODO: Allow overriding if an addressed email is on the good list? # If there are no sanitized addresses we can't override! sanitized_addresses = sanitize_addresses(type) # puts "override_email 4: #{type} - #{sanitized_addresses}" return [] if sanitized_addresses.empty? # At this point it is assured that the address list will need to be sanitized # One more check to ensure none of the configured sanitized email addresses are on the bad_list sanitized_addresses = clean_addresses(sanitized_addresses, :bad_list) # puts "override_email 5: #{type} - #{sanitized_addresses}" # If we don't want to inject the "email" in the "user name" section of the sanitized recipients, # then just return the default sanitized recipients return sanitized_addresses unless SanitizeEmail.use_actual_email_as_sanitized_user_name with_user_names = inject_user_names(real_addresses, sanitized_addresses) # puts "real_addresses 2: #{real_addresses}" # puts "override_email 6: #{type} - #{with_user_names}" # Otherwise inject the email as the "user name" with_user_names end def address_list_filter(list_type, address) # TODO: How does this handle email addresses with user names like "Foo Example <foo@example.org>" has_address = send(list_type).include?(address) case list_type when :good_list then has_address ? address : nil when :bad_list then has_address ? nil : address end end def inject_user_names(real_addresses, sanitized_addresses) real_addresses.each_with_object([]) do |real_recipient, result| new_recipient = if real_recipient.nil? sanitized_addresses else # puts "SANITIZED: #{sanitized_addresses}" sanitized_addresses.map { |sanitized| "#{real_recipient.gsub(REPLACE_AT[0], REPLACE_AT[1]).gsub(/[<>]/, '~')} <#{sanitized}>" } end result << new_recipient end.flatten end def clean_addresses(addresses, list_type) # Normalize addresses just in case it isn't an array yet addresses.map do |address| # If this address is on the good list then let it pass address_list_filter(list_type, address) end.compact.uniq end def sanitize_addresses(type) case type when :to then Array(sanitized_to) when :cc then Array(sanitized_cc) when :bcc then Array(sanitized_bcc) else raise UnknownOverride, 'unknown email override' end end end end
module Middleman module Dotenv class << self def registered(app, options_hash = {}) env = options_hash[:env] || '.env' require 'dotenv' unless defined?(::Dotenv) ::Dotenv.load File.join(Dir.pwd, env) app.before do ::Dotenv.load File.join(self.class.inst.root, env) end end alias_method :included, :registered end end end
# To change this template, choose Tools | Templates # and open the template in the editor. require File.expand_path(File.dirname(File.dirname(__FILE__)) + '/spec_helper') describe Parser do it "Should map http string to a URI" do Parser["http://example.com"].first.should be_a RDF::URI end it "Should parse svn to a URI" do Parser["svn:456/example.csv"].first.should be_a RDF::URI Parser["svn:456/example.csv"].first.should eql RDF::URI( "http://svn.amee.com/example.csv") #removed this tests while i'm not sure how to handle !svn/bc in the graphs #Parser["svn:456/example.csv"].first.should eql RDF::URI( # "http://svn.amee.com/!svn/bc/456/example.csv") #Parser["svn:6224/internal/api_csvs/business/agriculture/livestock/entericfermentation/sources/V4_10_Ch10_Livestock.pdf"]. # first.should eql RDF::URI("http://svn.amee.com/!svn/bc/6224/internal/api_csvs/business/agriculture/livestock/entericfermentation/sources/V4_10_Ch10_Livestock.pdf") end it "Should parse svn without version number to a URI" do Parser["svn:example.csv"].first.should eql RDF::URI("http://svn.amee.com/example.csv") end it "Should parse apicsvs to URI" do Parser["apicsvs:home/energy"].first. should eql RDF::URI("http://svn.amee.com/internal/api_csvs/home/energy") end it "Should parse csv files to several URIs" do Parser["csv_files:home/energy/electricity"]. should eql [ RDF::URI("http://svn.amee.com/internal/api_csvs/home/energy/electricity/default.js"), RDF::URI("http://svn.amee.com/internal/api_csvs/home/energy/electricity/itemdef.csv"), RDF::URI("http://svn.amee.com/internal/api_csvs/home/energy/electricity/data.csv") ] end it "Should parse anonymous to context" do Parser.context "svn:example.csv" Parser["anonymous:sad time"].should eql [RDF::URI("http://svn.amee.com/example.csv/anonymous/sad+time")] end it "should parse nouri to global" do Parser["nouri:sad time"].should eql [RDF::URI("http://xml.amee.com/provenance/global/anonymous/sad+time")] end it "should parse xls to no fragment" do Parser["http://foo.bar/wibble.xls#mysheet!$1$2"].should eql [RDF::URI("http://foo.bar/wibble.xls")] end it "should leave fragment on other extensions" do Parser["http://foo.bar/wibble.zib#myanchor"].should eql [RDF::URI("http://foo.bar/wibble.zib#myanchor")] end it "Should parse out a series of statements" do Statemented.enum_substatement( "amee:dummy",RDF.type,Prov::AMEE.category).to_a. should eql [RDF::Statement.new(RDF::URI("http://live.amee.com/data/dummy"), RDF.type,Prov::AMEE.category)] end end
require 'yaml' require 'fileutils' require 'pathname' require 'vcr' GEMS_PENDING_ROOT ||= File.expand_path(File.join(__dir__, "../..")) class TestEnvHelper attr_reader :relative_dir, :absolute_recording_dir, :config_file GEMS_PENDING_DIR = Pathname.new(GEMS_PENDING_ROOT) SPEC_DIR = GEMS_PENDING_DIR.join('spec') RECORDINGS_DIR = SPEC_DIR.join('recordings') # Set TEST_ENV_DIR environment variable, when recording. TEST_ENV_DIR = ENV['TEST_ENV_DIR'] ? Pathname.new(ENV['TEST_ENV_DIR']) : SPEC_DIR.join('test_env') CONFIG_DIR = TEST_ENV_DIR.join('config') GLOBAL_CONFIG_FILE = TEST_ENV_DIR.join('config.yml') def initialize(test_path) # <GEMS_PENDING_ROOT>/spec/some_dir1/some_dir2/some_spec.rb @test_file = Pathname.new(File.expand_path(test_path)) # <GEMS_PENDING_ROOT>/spec/some_dir1/some_dir2 @test_dir = @test_file.dirname # some_spec @test_basename = @test_file.basename(".rb") # some_dir1/some_dir2/some_spec @relative_dir = spec_relative_path(@test_dir).join(@test_basename) # <GEMS_PENDING_ROOT>/spec/recordings/some_dir1/some_dir2 @absolute_recording_dir = RECORDINGS_DIR.join(@relative_dir) # <GEMS_PENDING_ROOT>/spec/test_env/config/some_dir1/some_dir2/some_spec.yml @config_file = CONFIG_DIR.join("#{@relative_dir}.yml") end # # Global configuration. # def self.global_config @global_config ||= begin YAML.load_file(GLOBAL_CONFIG_FILE) rescue {} end end def self.global_config_values @global_config_values ||= global_config[:values] || {} end def self.global_config_filter @global_config_filter ||= global_config[:filter] || {} end def self.global_config_default @global_config_default ||= global_config[:default] || {} end # Global configuration values. def self.[](tag) global_config_values[tag] || global_config_filter[tag] || global_config_default[tag] end def self.recordings_dir pwd_relative_path(RECORDINGS_DIR) end def self.pwd_relative_path(path) pwd = Pathname.new(Dir.getwd) path.expand_path.relative_path_from(pwd) end # # Filter global values. # def self.vcr_filter(vcr_config) global_config_filter.each do |val_tag, replacement_text| next unless (value = global_config_values[val_tag]) vcr_config.filter_sensitive_data(replacement_text) { CGI.escape(value) } vcr_config.filter_sensitive_data(replacement_text) { value } end end # # Test-local configuration. # def config @config ||= begin YAML.load_file(@config_file) rescue => err puts err.to_s {} end end def global_config self.class.global_config end def global_config_values self.class.global_config_values end def global_config_filter self.class.global_config_filter end def global_config_default @self.class.global_config_default end def config_values @config_values ||= config[:values] || {} end def config_filter @config_filter ||= config[:filter] || {} end def config_default @config_default ||= config[:default] || {} end # Test-local configuration values - can override global. def [](tag) config_values[tag] || config_filter[tag] || config_default[tag] || self.class[tag] end # # Path and directory methods. # def cassette_for(id) File.join(@relative_dir, "#{@test_basename}#{id}") end def spec_relative_path(path) path.expand_path.relative_path_from(SPEC_DIR) end def pwd_relative_path(path) self.class.pwd_relative_path(path) end def ensure_recording_dir_exists FileUtils.mkdir_p(@absolute_recording_dir) end # # Filter test-specific values. # def vcr_filter VCR.configure do |c| config_filter.each do |val_tag, replacement_text| next unless (value = config_values[val_tag]) c.filter_sensitive_data(replacement_text) { CGI.escape(value) } c.filter_sensitive_data(replacement_text) { value } end end end end if __FILE__ == $PROGRAM_NAME env = TestEnvHelper.new(__FILE__) puts env.global_config.inspect puts puts env.config.inspect puts puts "RECORDINGS_DIR = #{TestEnvHelper::RECORDINGS_DIR}" puts "recordings_dir = #{TestEnvHelper.recordings_dir}" puts "absolute_recording_dir = #{env.absolute_recording_dir}" puts "relative_dir = #{env.relative_dir}" puts "config_file = #{env.config_file}" end
require "spec_helper" describe Paperclip do context ".run" do before do Paperclip.options[:log_command] = false expect(Terrapin::CommandLine).to receive(:new).with("convert", "stuff", {}).and_return(double(run: nil)) @original_command_line_path = Terrapin::CommandLine.path end after do Paperclip.options[:log_command] = true Terrapin::CommandLine.path = @original_command_line_path end it "runs the command with Terrapin" do Paperclip.run("convert", "stuff") end it "saves Terrapin::CommandLine.path that set before" do Terrapin::CommandLine.path = "/opt/my_app/bin" Paperclip.run("convert", "stuff") expect(Terrapin::CommandLine.path).to match("/opt/my_app/bin") end it "does not duplicate Terrapin::CommandLine.path on multiple runs" do expect(Terrapin::CommandLine).to receive(:new).with("convert", "more_stuff", {}).and_return(double(run: nil)) Terrapin::CommandLine.path = nil Paperclip.options[:command_path] = "/opt/my_app/bin" Paperclip.run("convert", "stuff") Paperclip.run("convert", "more_stuff") cmd_path = Paperclip.options[:command_path] assert_equal 1, Terrapin::CommandLine.path.scan(cmd_path).count end end it "does not raise errors when doing a lot of running" do Paperclip.options[:command_path] = ["/usr/local/bin"] * 1024 Terrapin::CommandLine.path = "/something/else" 100.times do |x| Paperclip.run("echo", x.to_s) end end context "Calling Paperclip.log without options[:logger] set" do before do Paperclip.logger = nil Paperclip.options[:logger] = nil end after do Paperclip.options[:logger] = ActiveRecord::Base.logger Paperclip.logger = ActiveRecord::Base.logger end it "does not raise an error when log is called" do silence_stream(STDOUT) do Paperclip.log("something") end end end context "Calling Paperclip.run with a logger" do it "passes the defined logger if :log_command is set" do Paperclip.options[:log_command] = true expect(Terrapin::CommandLine).to receive(:new).with("convert", "stuff", { logger: Paperclip.logger }).and_return(double(run: nil)) Paperclip.run("convert", "stuff") end end context "Paperclip.each_instance_with_attachment" do before do @file = File.new(fixture_file("5k.png"), "rb") d1 = Dummy.create(avatar: @file) d2 = Dummy.create d3 = Dummy.create(avatar: @file) @expected = [d1, d3] end after { @file.close } it "yields every instance of a model that has an attachment" do actual = [] Paperclip.each_instance_with_attachment("Dummy", "avatar") do |instance| actual << instance end expect(actual).to match_array @expected end end it "raises when sent #processor and the name of a class that doesn't exist" do assert_raises(LoadError) { Paperclip.processor(:boogey_man) } end it "returns a class when sent #processor and the name of a class under Paperclip" do assert_equal ::Paperclip::Thumbnail, Paperclip.processor(:thumbnail) end it "gets a class from a namespaced class name" do class ::One; class Two; end; end assert_equal ::One::Two, Paperclip.class_for("One::Two") end it "raises when class doesn't exist in specified namespace" do class ::Three; end class ::Four; end assert_raises NameError do Paperclip.class_for("Three::Four") end end context "An ActiveRecord model with an 'avatar' attachment" do before do rebuild_model path: "tmp/:class/omg/:style.:extension" @file = File.new(fixture_file("5k.png"), "rb") end after { @file.close } it "does not error when trying to also create a 'blah' attachment" do assert_nothing_raised do Dummy.class_eval do has_attached_file :blah end end end context "with a subclass" do before do class ::SubDummy < Dummy; end end it "is able to use the attachment from the subclass" do assert_nothing_raised do @subdummy = SubDummy.create(avatar: @file) end end after do SubDummy.delete_all begin Object.send(:remove_const, "SubDummy") rescue StandardError nil end end end it "has an avatar getter method" do assert Dummy.new.respond_to?(:avatar) end it "has an avatar setter method" do assert Dummy.new.respond_to?(:avatar=) end context "that is valid" do before do @dummy = Dummy.new @dummy.avatar = @file end it "is valid" do assert @dummy.valid? end end it "does not have Attachment in the ActiveRecord::Base namespace" do assert_raises(NameError) do ActiveRecord::Base::Attachment end end end context "configuring a custom processor" do before do @freedom_processor = Class.new do def make(file, _options = {}, _attachment = nil) file end end.new Paperclip.configure do |config| config.register_processor(:freedom, @freedom_processor) end end it "is able to find the custom processor" do assert_equal @freedom_processor, Paperclip.processor(:freedom) end after do Paperclip.clear_processors! end end end
require 'formula' class Shrinkler < Formula homepage 'https://bitbucket.org/askeksa/shrinkler/' url 'https://bitbucket.org/askeksa/shrinkler/downloads/shrinkler44.zip' version '4.4' sha256 'bc303c117332493f365a801d8f2088d4e823d0726c8efc769b619ceccde77a3d' def install File.rename 'MacOSX/Shrinkler', 'MacOSX/shrinkler' bin.install 'MacOSX/shrinkler' end end
require 'fs/MiqFS/MiqFS' require 'metadata/util/win32/system_path_win' module WinMountProbe WIN_FS_TYPES = ["FAT32", "NTFS", "ntfs"] def self.probe(fs) unless WIN_FS_TYPES.include?(fs.fsType) $log.debug "WinMountProbe << FALSE because file system (#{fs.fsType}) is not supported" if $log return false end begin si = Win32::SystemPath.systemIdentifier(fs) # This method will raise an error if it does not find the file system boot markers Win32::SystemPath.systemRoot(fs, si) return true rescue $log.debug "WinMountProbe << FALSE because #{$!} was found" if $log end false end end
# frozen_string_literal: true require 'set' require 'stannum/support' module Stannum::Support # Shared functionality for coercing values to and from constraints. module Coercion class << self ERROR_KEY_TYPES = Set.new([Integer, String, Symbol]).freeze private_constant :ERROR_KEY_TYPES # Coerces an arbitrary object into a valid Stannum::Errors key. # # If the value is an Integer, a String, or a Symbol, returns the value. # Otherwise, returns the result of calling #inspect on the value. # # @param value [Object] The value to coerce. # # @return [Integer, String, Symbol] the value or result of #inspect. def error_key(value) return value if ERROR_KEY_TYPES.include?(value.class) value.inspect end # Coerce a Boolean value to a Presence constraint. # # @param present [true, false, Stannum::Constraints::Base, nil] The # expected presence or absence of the value. If true, will return a # Presence constraint. If false, will return an Absence constraint. # @param allow_nil [true, false] If true, a nil value will be returned # instead of raising an exception. # @param as [String] A short name for the coerced value, used in # generating an error message. Defaults to "present". # @param options [Hash<Symbol, Object>] Configuration options for the # constraint. Defaults to an empty Hash. # # @yield Builds a constraint from true or false. If no block is given, # creates a Stannum::Constraints::Presence or # Stannum::Constraints::Absence constraint. # @yieldparam present [true, false] The expected presence or absence of # the value. # @yieldparam options [Hash<Symbol, Object>] Configuration options for the # constraint. Defaults to an empty Hash. # @yieldreturn [Stannum::Constraints::Base] the generated constraint. # # @return [Stannum::Constraints:Base, nil] the generated or given # constraint. def presence_constraint( present, allow_nil: false, as: 'present', **options, &block ) return nil if allow_nil && present.nil? if present.is_a?(Stannum::Constraints::Base) return present.with_options(**options) end if present == true || present == false # rubocop:disable Style/MultipleComparison return build_presence_constraint(present, **options, &block) end raise ArgumentError, "#{as} must be true or false or a constraint", caller(1..-1) end # Coerce a Class or Module to a Type constraint. # # @param value [Class, Module, Stannum::Constraints::Base, nil] The value # to coerce. # @param allow_nil [true, false] If true, a nil value will be returned # instead of raising an exception. # @param as [String] A short name for the coerced value, used in # generating an error message. Defaults to "type". # @param options [Hash<Symbol, Object>] Configuration options for the # constraint. Defaults to an empty Hash. # # @yield Builds a constraint from a Class or Module. If no block is given, # creates a Stannum::Constraints::Type constraint. # @yieldparam value [Class, Module] The Class or Module used to build the # constraint. # @yieldparam options [Hash<Symbol, Object>] Configuration options for the # constraint. Defaults to an empty Hash. # @yieldreturn [Stannum::Constraints::Base] the generated constraint. # # @return [Stannum::Constraints:Base, nil] the generated or given # constraint. def type_constraint( value, allow_nil: false, as: 'type', **options, &block ) return nil if allow_nil && value.nil? if value.is_a?(Stannum::Constraints::Base) return value.with_options(**options) end if value.is_a?(Module) return build_type_constraint(value, **options, &block) end raise ArgumentError, "#{as} must be a Class or Module or a constraint", caller(1..-1) end private def build_presence_constraint(present, **options) return yield(present, **options) if block_given? return Stannum::Constraints::Presence.new(**options) if present Stannum::Constraints::Absence.new(**options) end def build_type_constraint(value, **options) return yield(value, **options) if block_given? Stannum::Constraints::Type.new(value, **options) end end end end
class PostsController < ApplicationController def new end def create @post = Post.new(params[:post].permit(:title, :text)) @post.save redirect_to @post end private def post_params params.require(:post).permit(:title, :text) end def show @post = Post.find(params[:id]) end end
# frozen_string_literal: true require "cancancan" module ThinkFeelDoDashboard # Top level engine controller # inherits from host application's ApplicationController. class ApplicationController < ::ApplicationController include Concerns::BrowserDetective include Concerns::InvalidAuthToken before_action :authenticate_user!, :detect_browser check_authorization layout "application" rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, alert: exception.message end end end
include ActionDispatch::TestProcess FactoryGirl.define do factory :user do sequence(:email) { |n| "person_#{n}@example.com" } sequence(:name) { |n| "Person #{n}"} password 'password' end factory :contact_form do sequence(:email) { |n| "person_#{n}@example.com" } sequence(:name) { |n| "Person no.#{n}"} message "This is a message!" end factory :post do association :author, factory: :user association :topic, factory: :topic sequence(:title) { |n| "Post title #{n}" } description 'Post description' body 'Post body' factory :published_post do status "published" end end factory :topic do sequence(:name) { |n| "Topic #{n}" } end factory :news do sequence(:title) { |n| "Title #{n}" } sequence(:description) { |n| "Title #{n}" } sequence(:url) { |n| "http://someurl.com/#{n}" } published false factory :published_news do published true published_at Time.now end end factory :attachment do sequence(:image_file_name) { |n| "image#{n}.png" } image_file_size 1.megabyte image_content_type 'image/png' end end
begin require 'io/console' rescue LoadError end class Tb::Pager def self.open pager = self.new begin yield pager ensure pager.close end end def initialize if $stdout.tty? @io = nil @buf = '' else @io = $stdout @buf = nil end end def <<(obj) write obj.to_s self end def print(*args) s = '' args.map {|a| s << a.to_s } write s nil end def printf(format, *args) write sprintf(format, *args) nil end def putc(ch) if Integer === ch write [ch].pack("C") else write ch.to_s end ch end def puts(*objs) if objs.empty? write "\n" else objs.each {|o| o = o.to_s write o write "\n" if /\n\z/ !~ o } end nil end def write_nonblock(str) write str.to_s end def expand_tab(str, tabstop=8) col = 0 str.gsub(/(\t+)|[^\t]+/) { if $1 ' ' * (($1.length * tabstop) - (col + 1) % tabstop) else $& end } end DEFAULT_LINES = 24 DEFAULT_COLUMNS = 80 def winsize if $stdout.respond_to? :winsize lines, columns = $stdout.winsize return [lines, columns] if lines != 0 && columns != 0 end [DEFAULT_LINES, DEFAULT_COLUMNS] end def single_screen?(str) lines, columns = winsize n = 0 str.each_line {|line| line = expand_tab(line).chomp cols = line.length # xxx: 1 column/character assumed. cols = 1 if cols == 0 m = (cols + columns - 1) / columns # termcap am capability is assumed. n += m } n <= lines-1 end def write(str) str = str.to_s if !@io @buf << str if !single_screen?(@buf) @io = IO.popen(ENV['PAGER'] || 'more', 'w') @io << @buf @buf = nil end else @io << str end end def flush @io.flush if @io self end def close if !@io $stdout.print @buf else # don't need to ouput @buf because @buf is nil. @io.close if @io != $stdout end nil end end
require 'test_helper' class UsersControllerTest < ActionController::TestCase # Test index assigns variables test "should get index" do get :index assert_response :success assert_not_nil assigns(:users) assert_not_nil assigns(:inactive_users) end # Test new method test "should get new" do get :new assert_response :success end # Test Successful create user test "should create new user" do assert_difference('User.count', 1) do post :create, user: { username: "TestAdmin", password: "password", password_confirmation: "password" } end end # Test failure to create user because of password length test "should fail to create new user when password is too short" do assert_no_difference("User.count") do post :create, user: { username: "TestBadAdmin", password: "short", password_confirmation: "short" } end end # Test failure to create user because passwords don't match test "should fail to create new user when passwords don't match" do assert_no_difference("User.count") do post :create, user: { username: "TestBadAdmin", password: "password", password_confirmation: "password1" } end end end
class Pnameforms::Piece8sController < ApplicationController before_action :set_piece8, only: [:show, :edit, :update, :destroy] # GET /piece8s # GET /piece8s.json def index @pnameform = Pnameform.find(params[:pnameform_id]) @piece8s = @pnameform.piece8s end # GET /piece8s/8 # GET /piece8s/8.json def show @pnameform = Pnameform.find(params[:pnameform_id]) @piece8s = Piece8.all end # GET /piece8s/new def new @pnameform = Pnameform.find(params[:pnameform_id]) @piece8 = current_user.piece8s.build end # GET /piece8s/8/edit def edit @pnameform = Pnameform.find(params[:pnameform_id]) @piece8.pnameform = @pnameform end # POST /piece8s # POST /piece8s.json def create @pnameform = Pnameform.find(params[:pnameform_id]) @piece8 = current_user.piece8s.build(piece8_params) @piece8.pnameform = @pnameform respond_to do |format| if @piece8.save format.html { redirect_to pnameform_piece8s_path(@pnameform), notice: 'Piece8 was successfully created.' } format.json { render :show, status: :created, location: @piece8 } else format.html { render :new } format.json { render json: @piece8.errors, status: :unprocessable_entity } end end end # PATCH/PUT /piece8s/8 # PATCH/PUT /piece8s/8.json def update @pnameform = Pnameform.find(params[:pnameform_id]) @piece8.pnameform = @pnameform respond_to do |format| if @piece8.update(piece8_params) format.html { redirect_to pnameform_piece8s_path(@pnameform), notice: 'Piece8 was successfully updated.' } format.json { render :show, status: :ok, location: @piece8 } else format.html { render :edit } format.json { render json: @piece8.errors, status: :unprocessable_entity } end end end # DELETE /piece8s/8 # DELETE /piece8s/8.json def destroy @pnameform = Pnameform.find(params[:pnameform_id]) @piece8 = Piece8.find(params[:id]) title = @piece8.name if @piece8.destroy flash[:notice] = "\"#{title}\" was deleted successfully." redirect_to pnameform_piece8s_path(@pnameform) else flash[:error] = "There was an error deleting." render :show end end private # Use callbacks to share common setup or constraints between actions. def set_piece8 @piece8 = Piece8.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def piece8_params params.require(:piece8).permit(:name, :user_id) end end
class SharedBid < Bid attr_accessible :cut validates :cut, numericality: {only_integer: true} def total amount+cut end end
require 'rails_helper' describe ItemsController do describe "Item create" do before do @list = List.create(title: 'New list') @item = Item.create(body: 'New item', list_id: @list.id, ) end describe 'new item' do it "creates a new item on a particular list" do expect( @item.body ).to eq('New item') expect( @item.list_id ).to eq(@list.id) end end end end
require 'yaml' require 'singleton' require 'active_support/core_ext/hash/deep_merge' module StoryOffice class Configuration include Singleton def initialize # host = Socket.gethostname @conf_env = ENV['STORY_OFFICE_ENV'] || 'development' @config ||= read_yml_file(File.dirname(__FILE__) + '/../config/config.yml') config_env = read_yml_file(File.dirname(__FILE__) + "/../config/config_#{@conf_env.to_s.downcase}.yml") puts "Reading configuration from file config_#{@conf_env.to_s.downcase}.yml" if @config @config.deep_merge!(config_env) else @config = config_env end end def get_value(key) @config[key] end def read_yml_file(filename) if File.exist? filename YAML::load(File.read(filename, :encoding => 'UTF-8')) else {} end end end end
module Infrastructure class SharingServicesHead extend NamedParameter attr_reader :title attr_reader :description attr_reader :image attr_reader :type attr_reader :url attr_reader :site_name attr_reader :facebook_app_token alias fb_token facebook_app_token LOGO_IMAGE_PATH = 'images/logo.png' FACEBOOK_APP_TOKEN = "100000637301295" SITE_NAME = "HugoLnx::Blog" TYPE = 'article' named def initialize(post,request,url) @title = post.title @description = post.description @image = File.join("#{request.protocol}#{request.host}",LOGO_IMAGE_PATH) @type = TYPE @url = url @site_name = SITE_NAME @facebook_app_token = FACEBOOK_APP_TOKEN end def to_hash instance_variables.inject({}) do |hash,ivar| attr = ivar.to_s[/[^@]*$/] hash.merge(attr => public_send(attr)) end end end end
class AddImageListToStaticPages < ActiveRecord::Migration def change add_column :static_pages, :image_names, :json end end
# encoding: utf-8 module Mail module CommonField # :nodoc: include Mail::Constants def name=(value) @name = value end def name @name ||= nil end def value=(value) @length = nil @tree = nil @element = nil @value = value end def value @value end def to_s decoded.to_s end def default decoded end def field_length @length ||= "#{name}: #{encode(decoded)}".length end def responsible_for?( val ) name.to_s.casecmp(val.to_s) == 0 end private def strip_field(field_name, value) if value.is_a?(Array) value else value.to_s.sub(/\A#{field_name}:\s+/i, EMPTY) end end FILENAME_RE = /\b(filename|name)=([^;"\r\n]+\s[^;"\r\n]+)/ def ensure_filename_quoted(value) if value.is_a?(String) value.sub! FILENAME_RE, '\1="\2"' end end end end
require_relative '../../lib/ocr' describe OCR do describe '#parse_document' do context 'given a document with a valid account number of all 0s' do let(:path) { document_path('account_number_000000000.txt') } it 'should return a list of the parsed account numbers' do ocr = OCR.parse_document(path) expect(ocr.account_numbers).to eq ['000000000'] end end context 'given a document with a valid account number of all 1s' do let(:path) { document_path('account_number_111111111.txt') } it 'should return a list of the parsed account numbers' do ocr = OCR.parse_document(path) expect(ocr.account_numbers).to eq ['111111111'] end end context 'given a document with a valid account number ranging from 1-9' do let(:path) { document_path('account_number_123456789.txt') } it 'should return a list of the parsed account numbers' do ocr = OCR.parse_document(path) expect(ocr.account_numbers).to eq ['123456789'] end end end describe '#validated_account_numbers' do let(:path) { document_path('use_case_03.txt') } context 'given invalid account numbers' do it 'returns a list of validated account_numbers' do ocr = OCR.parse_document(path) validated = ocr.validated_account_numbers expect(validated[:invalid]).to eq ['111111111'] end end context 'given a list of valid account numbers' do it 'returns a list of validated account numbers' do ocr = OCR.parse_document(path) validated = ocr.validated_account_numbers expect(validated[:valid]).to eq ['000000051'] end end context 'given a list with illegible account_numbers' do it 'returns a list of validated account numbers' do ocr = OCR.parse_document(path) validated = ocr.validated_account_numbers expect(validated[:illegible]).to eq ["49006771?", "1234?678?"] end end end describe '#account_number_results' do let(:path) { document_path('use_case_03.txt') } let(:ocr) { OCR.parse_document(path) } context 'given a list of invalid bank account numbers' do it 'prints the results with an error status' do invalid_list = ocr.validated_account_numbers[:invalid] results = ocr.account_number_results(:invalid, invalid_list) expect(results).to eq "111111111 ERR\n" end end context 'given a list of illegible bank account numbers' do it 'prints the results with an illegible status' do illegible_list = ocr.validated_account_numbers[:illegible] results = ocr.account_number_results(:illegible, illegible_list) expect(results).to eq "49006771? ILL\n1234?678? ILL\n" end end context 'given a list of valid bank account numbers' do it 'prints the valid account numbers' do valid_list = ocr.validated_account_numbers[:valid] results = ocr.account_number_results(:valid, valid_list) expect(results).to eq "000000051\n" end end end end
# frozen_string_literal: true module Api class ApiController < ApplicationController before_action :skip_session_cookie before_action :set_api_version protect_from_forgery with: :null_session respond_to :json protected def included_params return [] if params[:include].nil? params['include'].split(',').map(&:strip) end def skip_session_cookie request.session_options[:skip] = true end def set_api_version accept_header = request.headers['Accept'] return if accept_header.nil? capture = accept_header.match(/version=(\d+)/).try(:captures) return if capture.nil? @api_version = capture[0].to_i end end end
class Exits extend Garb::Model metrics :visitors dimensions :visit_count end class HomeController < ApplicationController def index @github_repos = Project.where(:provider => 'github') @bitbucket_repos = Project.where(:provider => 'bitbucket') @heroku_apps = Project.where(:provider => 'heroku') end def fetch github = Octokit::Client.new(:login => ENV['github_username'], :password => ENV['github_password']) github.repositories('phatograph', :type => 'owner').each do |repo| Project.where({ :name => repo[:name], :provider => 'github' }).first_or_create!(:size => repo[:size]) end bitbucket = BitBucket.new :login => ENV['bitbucket_username'], :password => ENV['bitbucket_password'] bitbucket.repos.list.each do |repo| Project.where({ :name => repo[:name], :provider => 'bitbucket' }).first_or_create!(:size => repo[:size] / 1.kilobyte) end heroku = Heroku::API.new(:username => ENV['heroku_username'], :password => ENV['heroku_password']) heroku.get_apps.body.each do |repo| Project.where({ :name => repo['name'], :provider => 'heroku' }).first_or_create!(:size => repo['repo_size'] / 1.kilobyte) end render :text => '200' end def ga Garb::Session.login(ENV['google_username'], ENV['google_password']) profiles = Garb::Management::Profile.all profiles.each do |p| result = Exits.results(p, { :start_date => Date.today - 1, :end_date => Date.today }) puts p.web_property_id puts result.count end render :text => '200' end end
require 'spec_helper' describe TransactionInitiationsController do include Devise::TestHelpers before(:each) do sign_in_user :communicator, :as => :hulpverlener end def stub_find_starting_steps Step.stub :starting_steps => mock_steps end describe "GET new" do it "should assign starting steps as @starting_steps" do stub_find_starting_steps get :new assigns[:starting_steps].should == mock_steps end end describe "POST create" do def stub_successful_create stub_find_step stub_validation_successful stub_create_transaction stub_build_message stub_find_starting_steps end def stub_unsuccessful_create stub_find_step stub_validation_successful false stub_find_starting_steps end def stub_validation_successful success = true mock_transaction.stub :validate_initiation => nil mock_transaction.errors.stub :blank? => success end def stub_create_transaction stub_new(mock_transaction) mock_transaction.stub :initialized_at= mock_transaction.stub :definition= mock_transaction.stub \ :save => true, :update_uri => nil mock_step.stub :definition => mock_definition end def stub_find_step stub_find(mock_step) mock_transaction.stub :starting_step => mock_step.to_param end def stub_build_message mock_transaction.stub :messages => mock_messages stub_build_on mock_messages, mock_message mock_message.stub :save => true end describe "when invalid" do it "should redirect to new action" do stub_unsuccessful_create get :create response.should render_template('new') end it "should assign starting steps as @starting_steps" do stub_unsuccessful_create get :create assigns[:starting_steps].should == mock_steps end end describe "when successful" do it "should assign definition of step to transaction" do stub_successful_create mock_transaction.should_receive(:definition=).with(mock_definition) get :create end it "should assign unique uri to transaction" do stub_successful_create mock_transaction.should_receive(:update_uri).with(transaction_url(mock_transaction)) get :create end it "should redirect to the edit screen of created message" do stub_successful_create get :create response.should redirect_to(edit_message_url(mock_message)) end it "should flash successful message" do stub_successful_create get :create flash[:notice].should =~ /Transactie succesvol aangemaakt/ end end end end
Pod::Spec.new do |s| s.name = "Cadenza" s.version = "0.2.2" s.summary = "Useful categories" s.description = <<-DESC * can manage photo frame(edit/generating image). DESC s.homepage = "https://hanna.backlog.jp/projects/NH2014" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "Masaaki Goshima" => "masaaki.goshima@mixi.co.jp" } s.platform = :ios, '7.0' s.source = { :git => "hanna@hanna.git.backlog.jp:/IOS_LIB/Cadenza.git", :tag => "0.2.2" } s.source_files = 'Cadenza/**/*.{h,m}' s.requires_arc = true end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'static#home' resources :users resources :attractions resources :rides, only: [:create] get '/signin', to: 'session#new', as: 'signin' post '/session', to: 'session#create', as: 'session' get '/session', to: 'session#destroy' end
# class Hash # def keys_of(*arguments) # array = [] # self.each do |key, value| # arguments.each do |values| # if value == values # array << key # end # end # end # array # end # end class Hash def keys_of(*args) map {|key, value| args.include?(value) ? key : nil }.compact end end
class ChangeMediaToMedium < ActiveRecord::Migration[5.2] def change remove_reference :social_media_posts, :social_media add_reference :social_media_posts, :social_medium, index: true end end
class Dataservice::ConsoleContent < ActiveRecord::Base set_table_name :dataservice_console_contents belongs_to :console_logger, :class_name => "Dataservice::ConsoleLogger", :foreign_key => "console_logger_id" acts_as_list :scope => :console_logger_id include SailBundleContent # pagination default cattr_reader :per_page @@per_page = 5 self.extend SearchableModel @@searchable_attributes = %w{body console_logger_id} class <<self def searchable_attributes @@searchable_attributes end def display_name "Dataservice::ConsoleContent" end end end
require 'spec_helper' feature "User interacts with advanced search", :elasticsearch do background do star_wars_1 = Fabricate(:video, title: "Star Wars: Episode 1") star_wars_2 = Fabricate(:video, title: "Star Wars: Episode 2") star_trek = Fabricate(:video, title: "Star Trek") Fabricate(:video, title: "Bride Wars", description: "some wedding movie!") Fabricate(:review, video: star_wars_1, rating: 5, content: "awesome movie!!!") Fabricate(:review, video: star_wars_2, rating: 3) Fabricate(:review, video: star_trek, rating: 4) Fabricate(:review, video: star_trek, rating: 5) refresh_index login click_on "Advanced Search" end scenario "user searches with title" do within(".advanced_search") do fill_in "query", with: "Star Wars" click_button "Search" end expect(page).to have_content("2 videos found") expect(page).to have_content("Star Wars: Episode 1") expect(page).to have_content("Star Wars: Episode 2") expect(page).to have_no_content("Star Trek") end scenario "user searches with title and description" do within(".advanced_search") do fill_in "query", with: "wedding movie" click_button "Search" end expect(page).to have_content("Bride Wars") expect(page).to have_no_content("Star") end scenario "user searches with title, description and review" do within(".advanced_search") do fill_in "query", with: "awesome movie" check "Include Reviews" click_button "Search" end expect(page).to have_content "Star Wars: Episode 1" expect(page).to have_no_content "Star Wars: Episode 2" end scenario "user filters search results with average rating" do within(".advanced_search") do fill_in "query", with: "Star" check "Include Reviews" select "4.4", from: "rating_from" select "4.6", from: "rating_to" click_button "Search" end expect(page).to have_content "Star Trek" expect(page).to have_no_content "Star Wars: Episode 1" expect(page).to have_no_content "Star Wars: Episode 2" end end def refresh_index Video.import Video.__elasticsearch__.refresh_index! end
require 'rails' require 'toastrjs/rails/helper' module Toastrjs module Rails class Railtie < ::Rails::Railtie initializer "toastrjs.action_view" do ActiveSupport.on_load(:action_view) do include Toastrjs::Rails::Helper end end end end end