text
stringlengths
10
2.61M
class Product < ActiveRecord::Base attr_accessible :name, :price, :description, :image_url has_many :reviews validates_uniqueness_of :name validates_presence_of :name, :price end
require 'rails_helper' describe User do it "is valid with a name" do expect(User.new(name: 'test_user')).to be_valid end it "is invalid without a name" do user = User.new(name: nil) user.valid? expect(user.errors[:name]).to include("can't be blank") end end
class DiaperDrivesController < ApplicationController include Importable before_action :set_diaper_drive, only: [:show, :edit, :update, :destroy] def index setup_date_range_picker @diaper_drives = current_organization .diaper_drives .class_filter(filter_params) .within_date_range(@selected_date_range) .order(created_at: :desc) @selected_name_filter = filter_params[:by_name] end # GET /diaper_drives/1 # GET /diaper_drives/1.json def create @diaper_drive = current_organization.diaper_drives.new(diaper_drive_params.merge(organization: current_organization)) respond_to do |format| if @diaper_drive.save format.html { redirect_to diaper_drives_path, notice: "New diaper drive added!" } format.js else flash[:error] = "Something didn't work quite right -- try again?" format.html { render action: :new } format.js { render template: "diaper_drives/new_modal.js.erb" } end end end def new @diaper_drive = current_organization.diaper_drives.new if request.xhr? respond_to do |format| format.js { render template: "diaper_drives/new_modal.js.erb" } end end end def edit @diaper_drive = current_organization.diaper_drives.find(params[:id]) end def show @selected_name_filter = filter_params[:by_name] @diaper_drive = current_organization.diaper_drives.includes(:donations).find(params[:id]) end def update @diaper_drive = current_organization.diaper_drives.find(params[:id]) if @diaper_drive.update(diaper_drive_params) redirect_to diaper_drives_path, notice: "#{@diaper_drive.name} updated!" else flash[:error] = "Something didn't work quite right -- try again?" render action: :edit end end def destroy current_organization.diaper_drives.find(params[:id]).destroy respond_to do |format| format.html { redirect_to diaper_drives_url, notice: 'Diaper drive was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_diaper_drive @diaper_drive_info = DiaperDrive.find(params[:id]) end def diaper_drive_params params.require(:diaper_drive) .permit(:name, :start_date, :end_date) end def date_range_filter return '' unless params.key?(:filters) params.require(:filters)[:date_range] end def filter_params return {} unless params.key?(:filters) params.require(:filters).slice(:by_name) end end
class FontIosevkaEtoile < Formula version "18.0.0" sha256 "c3e3276f1a6744fc2c64ef795e5698ca241cf660b74ed7738858f5de77220d4a" url "https://github.com/be5invis/Iosevka/releases/download/v#{version}/ttc-iosevka-etoile-#{version}.zip" desc "Iosevka Etoile" desc "Sans-serif, slab-serif, monospace and quasi‑proportional typeface family" homepage "https://github.com/be5invis/Iosevka/" def install (share/"fonts").install "iosevka-etoile-bold.ttc" (share/"fonts").install "iosevka-etoile-extrabold.ttc" (share/"fonts").install "iosevka-etoile-extralight.ttc" (share/"fonts").install "iosevka-etoile-heavy.ttc" (share/"fonts").install "iosevka-etoile-light.ttc" (share/"fonts").install "iosevka-etoile-medium.ttc" (share/"fonts").install "iosevka-etoile-regular.ttc" (share/"fonts").install "iosevka-etoile-semibold.ttc" (share/"fonts").install "iosevka-etoile-thin.ttc" end test do end end
class ScoreEvent < ActiveRecord::Base belongs_to :user validates_presence_of :score validates_presence_of :event validates_presence_of :user_id before_create :get_created_day after_create :push_notification def get_created_day self.created_day = Date.today end def self.user_score_events(user,params) MamashaiTools::ToolUtil.clear_unread_infos(user,:unread_invited_count) ScoreEvent.paginate(:per_page => 25,:conditions=>['user_id=?',user.id],:page => params[:page],:order => "id desc") end def self.old_score_events(user,params) MamashaiTools::ToolUtil.clear_unread_infos(user,:unread_invited_count) ScoreEvent.paginate(:per_page => 25,:page => params[:page],:conditions=>["user_id = ?",user.id],:order=>"id desc",:from=>"score_events_2010_08_20") end def push_notification if self.score > 0 MamashaiTools::ToolUtil.push_aps(self.user_id, "#{event_description},获得#{self.score}个晒豆。", {"t"=>"score"}) elsif self.score < 0 MamashaiTools::ToolUtil.push_aps(self.user_id, "#{event_description},扣除#{self.score.abs}个晒豆。", {"t"=>"score"}) end end end
class AddIsActiveToParticularPaymentAndDiscounts < ActiveRecord::Migration def self.up add_column :particular_payments, :is_active, :boolean, :default => true add_column :particular_discounts, :is_active, :boolean, :default => true add_index :particular_payments, :is_active, :name => "is_active" add_index :particular_discounts, :is_active, :name => "is_active" end def self.down remove_index :particular_discounts, :name => "is_active" remove_index :particular_payments, :name => "is_active" remove_column :particular_discounts, :is_active remove_column :particular_payments, :is_active end end
class CreateLikesAndFbLikes < ActiveRecord::Migration def up create_table :fb_likes do |t| t.string :fb_id t.string :name t.string :category t.datetime :created_time # when did the user like this t.timestamps end create_table :likes do |t| t.references :user t.integer :likee_id t.string :likee_type end end def down drop_table :fb_likes drop_table :likes end end
class Unit attr_reader :health_points, :attack_power def initialize(hp, ap) @health_points = hp @attack_power = ap end def attack!(enemy, ap_mod = 1) raise DeadAttackError if self.dead? enemy.damage((attack_power * ap_mod.to_f).ceil.to_i) end def damage(ap) raise DeadDamageError if self.dead? @health_points -= ap end def dead? health_points <= 0 end end
# frozen_string_literal: true module Bolt class Plugin class EnvVar def initialize(*_args); end def name 'env_var' end def hooks %i[resolve_reference validate_resolve_reference] end def validate_resolve_reference(opts) unless opts['var'] raise Bolt::ValidationError, "env_var plugin requires that the 'var' is specified" end unless ENV[opts['var']] raise Bolt::ValidationError, "env_var plugin requires that the var '#{opts['var']}' be set" end end def resolve_reference(opts) ENV[opts['var']] end end end end
module Scaffoldable extend ActiveSupport::Concern included do MODEL_CLASS = self.model_class before_action :set_object, only: [:show, :profile, :update, :destroy] end def index @temp = MODEL_CLASS set_model_collection end def show end def new set_model_instance(MODEL_CLASS.new) end def edit end def create set_model_instance(MODEL_CLASS.new(object_params)) respond_to do |format| if model_instance.save format.html { redirect_to model_instance, notice: "#{MODEL_CLASS.name} was successfully created." } format.json { render action: 'show', status: :created, location: model_instance } else format.html { render action: 'new' } format.json { render json: model_instance.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if model_instance.update(object_params) format.html { redirect_to model_instance, notice: "#{MODEL_CLASS.name} was successfully updated." } format.json { render action: 'show', status: :ok, location: model_instance } else format.html { render action: 'edit' } format.json { render json: model_instance.errors, status: :unprocessable_entity } end end end def destroy model_instance.destroy respond_to do |format| format.html { redirect_to send("#{MODEL_CLASS.table_name}_path") } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_object set_model_instance(MODEL_CLASS.find(params[:id])) end def set_model_instance(val) instance_variable_set("@#{MODEL_CLASS.name.underscore}", val) end def set_model_collection instance_variable_set("@#{MODEL_CLASS.name.pluralize.underscore}", MODEL_CLASS.all) end def model_instance instance_variable_get("@#{MODEL_CLASS.name.underscore}") end end
class Player < ActiveRecord::Base belongs_to :room belongs_to :user has_one :area, dependent: :nullify def start_from_center? room.game.start_from_center? end def camera_rotate (area.nil? || start_from_center?) ? 0 : 360 - area.angle end def start_center return [0, 0] if area.nil? || start_from_center? case area.angle when 0 [area.center_x, area.top_y] when 90 [area.right_x, area.center_y] when 180 [area.center_x, area.bottom_y] when 270 [area.left_x, area.center_y] else [0, 0] end end end
# MongoidSphinx, a full text indexing extension for MongoDB/Mongoid using # Sphinx. module Mongoid module Sphinx extend ActiveSupport::Concern included do unless defined?(SPHINX_TYPE_MAPPING) SPHINX_TYPE_MAPPING = { 'Date' => 'timestamp', 'DateTime' => 'timestamp', 'Time' => 'timestamp', 'Float' => 'float', 'Integer' => 'int', 'BigDecimal' => 'float', 'Boolean' => 'bool', 'String' => 'string', 'Object' => 'string', 'Array' => 'string' } end cattr_accessor :search_fields cattr_accessor :search_attributes cattr_accessor :index_options end module ClassMethods def search_index(options={}) self.search_fields = options[:fields] self.search_attributes = {} self.index_options = options[:options] || {} attribute_types = options[:attribute_types] || {} options[:attributes].each do |attrib| attr_type = attribute_types[attrib] || (self.fields[attrib.to_s] == nil ? nil : self.fields[attrib.to_s].type) if attr_type.blank? puts "MONGOID SPHINX WARRING: #{attrib} skiped, it need to define type in :attribute_types when it not define in :fields." next end self.search_attributes[attrib] = SPHINX_TYPE_MAPPING[attr_type.to_s] || 'str2ordinal' end MongoidSphinx.context.add_indexed_model self end def generate_id(object_id) #只支持两种类型的主键,且要保证转换后互相不能重复:BSON::ObjectId,Integer. #BSON::ObjectId通过crc32转换为数字 if object_id.is_a?(BSON::ObjectId) id=object_id.to_s.to_crc32 else raise RuntimeError,"MongoidSphinx require Id must be BSON::ObjectId or Integer" if object_id.is_a?(Integer)==false id=object_id.to_s.to_crc32 end return id end def internal_sphinx_index MongoidSphinx::Index.new(self) end def has_sphinx_indexes? self.search_fields && self.search_fields.length > 0 end def to_riddle self.internal_sphinx_index.to_riddle end def sphinx_stream STDOUT.sync = true # Make sure we really stream.. puts '<?xml version="1.0" encoding="utf-8"?>' puts '<sphinx:docset xmlns:sphinx="http://www.redstore.cn/">' # Schema puts '<sphinx:schema>' puts '<sphinx:field name="classname"/>' self.search_fields.each do |name| puts "<sphinx:field name=\"#{name}\"/>" end #需要区分主键是否是Integer类型,必须用bigint,因为可能大于32bit.暂时不这样做,因为id类型不一致,会在使用MongoidSphinx.search时发生错误. #if self.fields["_id"].type==Integer # puts "<sphinx:attr name=\"_id\" type=\"bigint\" />" #else # puts "<sphinx:attr name=\"_id\" type=\"string\" />" #end puts "<sphinx:attr name=\"_id\" type=\"string\" />" puts "<sphinx:attr name=\"classname\" type=\"string\" />" self.search_attributes.each do |key, value| puts "<sphinx:attr name=\"#{key}\" type=\"#{value}\" />" end puts '</sphinx:schema>' self.all.each do |document| sphinx_compatible_id = self.generate_id(document['_id']) puts "<sphinx:document id=\"#{sphinx_compatible_id}\">" puts "<classname>#{self.to_s}</classname>" puts "<_id>#{document.send("_id")}</_id>" self.search_fields.each do |key| if document.respond_to?(key.to_sym) value = document.send(key) value = value.join(",") if value.class == [].class puts "<#{key}>#{value.to_s}</#{key}>" end end self.search_attributes.each do |key, value| next if self.search_fields.include?(key) value = case value when 'bool' document.send(key) ? 1 : 0 when 'timestamp' document.send(key).to_i else document.send(key) end value = value.join(",") if value.class == [].class puts "<#{key}>#{value.to_s}</#{key}>" end puts '</sphinx:document>' end puts '</sphinx:docset>' end #返回xml #file:写入到文件 def sphinx_xml(file=false) require 'builder' #如果是写入文件中 if file xml = Builder::XmlMarkup.new(:indent=>2,:target => file) else xml = Builder::XmlMarkup.new(:indent=>2) end #生成<?xml version="1.0" encoding="UTF-8"?> xml.instruct! #docset--start xml.sphinx(:docset,"xmlns:sphinx"=>"http://www.redstore.cn/") do #schema--start xml.sphinx(:schema) do xml.sphinx(:field,"name"=>"classname") self.search_fields.each do |name| xml.sphinx(:field,"name"=>name) end #需要区分主键是否是Integer类型,必须用bigint,因为可能大于32bit.暂时不这样做,因为id类型不一致,会在使用MongoidSphinx.search时发生错误. #if self.fields["_id"].type==Integer # xml.sphinx(:attr,"name"=>"_id","type"=>"bigint") #else # xml.sphinx(:attr,"name"=>"_id","type"=>"string") #end xml.sphinx(:attr,"name"=>"_id","type"=>"string") xml.sphinx(:attr,"name"=>"classname","type"=>"string") self.search_attributes.each do |key, value| xml.sphinx(:attr,"name"=>key,"type"=>value) end end#schema--end #document--start self.all.each do |document| sphinx_compatible_id = self.generate_id(document['_id']) xml.sphinx(:document,"id"=>sphinx_compatible_id) do xml.classname(self.to_s) xml._id(document.send("_id")) self.search_fields.each do |key| if document.respond_to?(key.to_sym) value = document.send(key) value = value.join(",") if value.class == [].class #eval有危险 #eval("xml.#{key}('#{value.to_s}')") #xml.method_missing(key,value.to_s) #去掉html标签 xml.method_missing(key,value.to_s.gsub(/<\/?[^>]*>/, "")) end end self.search_attributes.each do |key, value| next if self.search_fields.include?(key) value = case value when 'bool' document.send(key) ? 1 : 0 when 'timestamp' document.send(key).to_i else document.send(key) end value = value.join(",") if value.class == [].class xml.method_missing(key,value.to_s.gsub(/<\/?[^>]*>/, "")) end end end#document--end end#docset--end #如果是写入文件中 if file return true else return xml.target! end end def search(query, options = {}) client = MongoidSphinx::Configuration.instance.client #修改默认的匹配模式是extended2 client.match_mode = options[:match_mode] || :extended2 client.offset = options[:offset].to_i if options.key?(:offset) client.limit = options[:limit].to_i if options.key?(:limit) client.limit = options[:per_page].to_i if options.key?(:per_page) client.offset = (options[:page].to_i - 1) * client.limit if options[:page] client.max_matches = options[:max_matches].to_i if options.key?(:max_matches) classes = options[:classes] || [] classes << self class_indexes = classes.collect { |klass| "#{klass.to_s.downcase}_core" }.flatten.uniq client.set_anchor(*options[:geo_anchor]) if options.key?(:geo_anchor) if options.key?(:sort_by) #注意,不是extended2 client.sort_mode = :extended client.sort_by = options[:sort_by] end #增加字段权重 #field_weights = {'title' => 10, 'artist' => 10, 'description' => 5, 'search_words'=> 5} if options.key?(:field_weights) client.field_weights = options[:field_weights] end #增加评价模式的指定 if options.key?(:rank_mode) client.rank_mode = options[:rank_mode] end if options.key?(:with) options[:with].each do |key, value| client.filters << Riddle::Client::Filter.new(key.to_s, value.is_a?(Range) ? value : value.to_a, false) end end if options.key?(:without) options[:without].each do |key, value| client.filters << Riddle::Client::Filter.new(key.to_s, value.is_a?(Range) ? value : value.to_a, true) end end result = client.query query, class_indexes.join(',') MongoidSphinx::Search.new(client, self, result) end end end end
class Bank attr_reader :name def initialize(name) @name = name.to_sym end def open_account(person) person.bank_accounts[name] = { galleons: 0, silver_sickles: 0, bronze_knuts: 0 } end def deposit(person, deposit) return no_account_message(person) if not has_account?(person) if has_enough_cash?(person, deposit) add_to_account(person, deposit) remove_from_cash(person, deposit) else not_enough_cash_for_deposit_message(person, deposit) end end def withdrawal(person, withdrawal) return no_account_message(person) if not has_account?(person) if has_enough_in_account?(person, withdrawal) remove_from_account(person, withdrawal) add_to_cash(person, withdrawal) else not_enough_in_account_message(person, withdrawal, :withdrawal) end end def transfer(person, other_bank, transfer) if has_accounts_with_both?(person, other_bank) if has_enough_in_account?(person, transfer) remove_from_account(person, transfer) other_bank.add_to_account(person, transfer) else not_enough_in_account_message(person, transfer, :transfer) end else no_account_message_banks(person, other_bank) end end def add_to_account(person, deposit) deposit.each do |denomination, amount| person.bank_accounts[name][denomination] += amount end end def remove_from_account(person, withdrawal) withdrawal.each do |denomination, amount| person.bank_accounts[name][denomination] -= amount end end def add_to_cash(person, withdrawal) withdrawal.each do |denomination, amount| person.cash[denomination] += amount end end def remove_from_cash(person, deposit) deposit.each do |denomination, amount| person.cash[denomination] -= amount end end def total_cash(person) return no_account_message(person) if not has_account?(person) total_cash = person.bank_accounts[name].reduce("") do |cash_string, (denomination, amount)| cash_string += " and #{amount} #{denomination.to_s.sub('_', ' ')}" unless denomination == :galleons if denomination == :galleons cash_string += "#{person.name} has #{amount} #{denomination.to_s.sub('_', ' ')}" end cash_string end end def has_account?(person) person.bank_accounts.key?(name) end def has_accounts_with_both?(person, other_bank) has_account?(person) && other_bank.has_account?(person) end def no_account_message(person) "#{person.name} does not have an account with #{name}" end def no_account_message_banks(person, other_bank) unless other_bank.has_account?(person) other_bank.no_account_message(person) else no_account_message(person) end end def not_enough_cash_for_deposit_message(person, deposit) currency = deposit.find do |denomination, amount| amount > person.cash[denomination] end "#{person.name} does not have enough #{currency[0].to_s.sub('_', ' ')} for this deposit" end def not_enough_in_account_message(person, withdrawal_or_transfer, type) currency = withdrawal_or_transfer.find do |denomination, amount| amount > person.bank_accounts[name][denomination] end "#{person.name} does not have enough #{currency[0].to_s.sub('_', ' ')} in their account for this #{type.to_s}" end def calculate_value(currencies) silver_sickles = currencies[:silver_sickles] + change(:silver_sickles, :bronze_knuts, currencies[:bronze_knuts]) bronze_knuts = currencies[:bronze_knuts] % 29 final_value = { galleons: currencies[:galleons], silver_sickles: silver_sickles, bronze_knuts: bronze_knuts } end def change(to_currency, from_currency, amount) if from_currency == :galleons to_currency == :silver_sickles ? amount * 17 : amount * 493 elsif from_currency == :silver_sickles to_currency == :galleons ? amount / 17 : amount * 29 else to_currency == :galleons ? amount / 493 : amount / 29 end end def has_enough_cash?(person, deposit) enough = true deposit.each do |denomination, amount| enough = false if amount > person.cash[denomination] end enough end def has_enough_in_account?(person, withdrawal) enough = true withdrawal.each do |denomination, amount| enough = false if amount > person.bank_accounts[name][denomination] end enough end end
class AdministerUsersController < ApplicationController before_action :authenticate_user! before_action :require_admin def edit @user = User.find(params[:id]) session[:return_to] ||= request.referer end def index session[:return_to]="" session.delete(:return_to) @users = User.where.not(id: current_user.id).order("first_name ASC, last_name ASC").page(params[:page]).per(10) end def show @user = User.find(params[:id]) render 'edit' end def update @user = User.find(params[:id]) unless @user.admin? then if @user.update(administer_user_params) flash[:notice] = "User updated " if params[:send_email] == '1' AdminMailer.admin_to_user_email(@user).deliver_now end redirect_to administer_user_url(@user) else flash[:alert] = "Cannot update user" render 'edit' end else if (@user.admin? && User.admins_count > 1) # will update admin in case he is not last in system if @user.update(administer_user_params) flash[:notice] = "User with Admin role updated" redirect_to administer_user_url(@user) # last admin in the system cannot be changed! else flash[:alert] = "Cannot update last admin in system - use My Account to change alowed" render 'edit' end end end end def destroy @user = User.find(params[:id]) @user.destroy flash[:notice] = "User destroyed." redirect_to administer_users_url end private def administer_user_params params.require(:user).permit(:id, :first_name, :last_name, :role, :status, :notifications, :message, :send_email, :profile_image ) end end
# Description: # You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array. # Example: longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta" # n being the length of the string array, if n = 0 or k > n or k <= 0 return "". # Pseudocode: # Go through the array and group the strings together according to the k integer value # join these smaller arrays and count their lengths # if the consecutive strings ahead of the current strings is larger, keep that one # else, return the current one # afterwards, go back and add the edge case conditionals: # if strarr.length == 0, or k > strarr.length, or k <=0, return "" # Solution 1: def longest_consec(strarr, k) return "" if (strarr.length == 0) || (k > strarr.length) || (k <= 0) consecutive_strings = [] n = 0 while n <= strarr.length do consecutive_strings << strarr.slice(n...(n+k)).join n += 1 end final = [""] consecutive_strings.each do |string| if (string != "") && (string.length > final[0].length) final.unshift(string) end end final.first end # Solution 2: def longest_consec(strarr, k) return "" if (strarr.length == 0) || (k > strarr.length) || (k <= 0) consecutive_strings = strarr.each_cons(k).map { |strings| strings.join } final = [""] consecutive_strings.each do |string| if string.length > final[0].length final.unshift(string) end end final.first end # Solution 3: def longest_consec(strarr, k) return "" if (strarr.length == 0) || (k > strarr.length) || (k <= 0) strarr.each_cons(k).map { |strings| strings.join }.max_by { |str| str.length } end # Tests: result = longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) solution = "abigailtheta" puts (result == solution ? "Correct!" : "Wrong!")
class Benchwarmer attr_reader :results class << self def run(options = {gc: :enable}) if options[:gc] == :disable GC.disable elsif options[:gc] == :enable # collect memory allocated during library loading # and our own code before the measurement GC.start end memory_before = memory_snapshot gc_stat_before = GC.stat time = Benchmark.realtime do yield end gc_stat_after = GC.stat GC.start if options[:gc] == :enable memory_after = memory_snapshot new( { ruby_version: RUBY_VERSION, time: time.round(2), gc: options[:gc], gc_count_after: gc_stat_after[:count].to_i, gc_count_before: gc_stat_before[:count].to_i, memory_after: memory_after, memory_before: memory_before } ) end private def memory_snapshot `ps -o rss= -p #{Process.pid}`.to_i/1024 end end def initialize(results) @results = results end def gc @results[:gc] end def time(round_by:2) @results[:time].round(round_by) end def gc_count @results[:gc_count_after] - @results[:gc_count_before] end def ruby_version @results[:ruby_version] end def memory @results[:memory_after] - @results[:memory_before] end def save_report(location:nil, name:, format: nil) location = location.nil? ? "#{Rails.root}/benchmarks" : "#{Rails.root}/#{location}" output = print_report(format: format) extension = format == :json ? 'json' : 'txt' file_name = "#{name}.#{extension}" File.open("#{location}/#{file_name}", "w+") do |f| f.puts output end end def report { ruby_version: ruby_version, gc: gc.to_s, time: time, gc_count: gc_count, memory: "%d MB" % memory } end def print_report(format: nil) return "Please choose :json, :text" unless [:json, :text, nil].include?(format) return text_report unless format == :json json_report end private def text_report printed_report = "" report.each { |k, v| printed_report << "#{k}: #{report.fetch(k)} " } printed_report end def json_report report.to_json end end
class CreatePushes < ActiveRecord::Migration[5.2] def change create_table :pushes do |t| t.references :commits, foreign_key: true t.references :repository, foreign_key: true t.datetime :pushed_at t.references :pusher, foreign_key: true t.timestamps end end end
# frozen_string_literal: true module MarkdownMetrics module Elements module Block class Table < MarkdownMetrics::Elements::Base def self.match_element(line, next_line) line.to_s.match(/^.* \| .*$/) && next_line.to_s.match(/^\-{1,} \| \-{1,}$/) end def name :table end def value headers = current_line.split("|") rows = [] end_line = nil next_line = @start_at @lines[(@start_at + 2)..-1].each do |code_line| next_line += 1 unless code_line.match(/^.* \| .*$/) end_line = next_line break end end_line = @lines.size - 1 if end_line.nil? end if !end_line.nil? @skip_lines_until = end_line @lines[@start_at+2..end_line].each do |row_line| rows << row_line.split("|") end { rows: rows, headers: headers } end end end end end end
require 'rails_helper' RSpec.describe User, :type => :model do before { @user = User.new(name: "Example User", email: "user@example.com", password: "foobar", password_confirmation: "foobar", mtname: 'example') } subject { @user } it { should respond_to(:name) } it { should respond_to(:email) } it { should respond_to(:password) } it { should respond_to(:letters) } it { should respond_to(:password_confirmation) } it { should respond_to(:remember_token) } it { should respond_to(:authenticate) } it { should be_valid } describe "remember token" do before { @user.save } it { expect(@user.remember_token).not_to be_blank } end describe "when name not present" do before { @user.name = '' } it { should_not be_valid } end describe "when mtname is upcased" do before do @user.mtname = 'Coolz' @user.save end it "saves it as lowercase" do expect(@user.mtname).to eq 'coolz' end end describe "when email not present" do before { @user.email = '' } it { should_not be_valid } end describe "when name is already taken" do before do user_with_same_name = @user.dup user_with_same_name.save end it { should_not be_valid } end describe "when a password is not present" do before { @user = User.new(name: "Example User", email: "user@example.com", password: "", password_confirmation: "")} it { should_not be_valid } end describe "when a password doesn't match confirmation" do before { @user.password_confirmation= "mismatch" } it { should_not be_valid } end describe "with a password that's too short" do before { @user.password = @user.password_confirmation = 'a'*5 } it { should be_invalid } end describe "return value of authenticate method" do before { @user.save } let(:found_user) { User.find_by(email: @user.email) } describe "with a valid password" do it { should eq found_user.authenticate(@user.password) } end describe "with an invalid password" do let(:user_for_invalid_password) { found_user.authenticate("invalid") } it { should_not eq user_for_invalid_password } specify { expect(user_for_invalid_password).to be_falsey } end end describe "letters associations" do before { @user.save } let!(:older_letter) { FactoryGirl.create(:letter, user: @user, created_at: 1.day.ago) } let!(:newer_letter) { FactoryGirl.create(:letter, user: @user, created_at: 1.hour.ago) } it "should have the right letters in the right order" do expect(@user.letters).to eq [newer_letter, older_letter] end it "should destroy associated letters" do letters = @user.letters.to_a @user.destroy expect(letters).to_not be_empty letters.each do |letter| expect(Letter.where(id:letter.id)).to be_empty end end end end
class AddContactInfoToStores < ActiveRecord::Migration def change add_column :stores, :franchise_number, :string add_column :stores, :phone, :integer add_column :stores, :franchisee_name, :string add_column :stores, :contact_name, :string add_column :stores, :contact_phone, :integer end end
# frozen_string_literal: true require "spec_helper" RSpec.describe Tikkie::Api::V1::Responses::BankAccount do subject { Tikkie::Api::V1::Responses::BankAccount.new(user[:bankAccounts].first) } let(:users) { JSON.parse(File.read("spec/fixtures/responses/v1/users/list.json"), symbolize_names: true) } let(:user) { users.first } describe '#bank_account_token' do it 'returns the bank_account_token' do expect(subject.bank_account_token).to eq("bankaccounttoken1") end end describe '#bank_account_label' do it 'returns the bank_account_label' do expect(subject.bank_account_label).to eq("Personal account") end end describe '#iban' do it 'returns the iban' do expect(subject.iban).to eq("NL02ABNA0123456789") end end end
require 'forwardable' module Mikon # Internal class for indexing class Index extend Forwardable def_delegators :@data, :[] def initialize(source, options={}) options = { name: nil }.merge(options) case when source.is_a?(Array) @data = Mikon::DArray.new(source) when source.is_a?(Mikon::DArray) @data = source else raise ArgumentError end @name = options[:name] end def sort_by(&block) return self.to_enum(:sort_by) unless block_given? Mikon::Index.new(@data.sort_by(&block)) end end end
require 'level_object/mixin/jumper' shared_examples 'jumper' do before do described_class.jump_power = 10 end it { should respond_to :jump_power } context '#jump_power' do its(:jump_power) { should == 10 } end context '#jump' do context 'on ground' do before do subject.on_ground = false end it 'should not change velocity' do expect { subject.jump }.not_to change(subject, :vel_y) end end context 'not on ground' do before do subject.on_ground = true end it 'should not change velocity' do expect { subject.jump }.to change(subject, :vel_y).by(-10) end end end end
class Order < ApplicationRecord belongs_to :user has_many :placements, dependent: :destroy has_many :products, through: :placements attribute :total def total placements.sum{ |place| place.product.price.*(place.quantity) } end end
class DropCarts < ActiveRecord::Migration def change execute "DROP TABLE carts" end end
require 'spec_helper' describe Fappu::Page do describe "#new_from_json" do let(:args) { {'1' => {'image' => 'http://a.url.com', 'thumb' => 'http://a.thumb_url.com'}}} subject{ described_class.new_from_json(args) } it { is_expected.to be_an_instance_of(described_class) } it { is_expected.to have_attributes( page_number: '1', image_url: 'http://a.url.com', thumbnail_url: 'http://a.thumb_url.com' )} end end
#require 'singleton' #path = File.expand_path '..', __FILE__ #$LOAD_PATH.unshift path unless $LOAD_PATH.include?(path) #path = File.expand_path '../../../../shared-test-ruby', __FILE__ #$LOAD_PATH.unshift path unless $LOAD_PATH.include?(path) # All the HTML Elements the tests need to access in order to conduct text search class TextSearchContainer < AccessBrowserV2 include Singleton def initialize super add_action(CucumberLabel.new("Text Search Field"), SendKeysAndEnterAction.new, AccessHtmlElement.new(:id, "searchtext")) add_action(CucumberLabel.new("Text Search"), SendKeysAction.new, AccessHtmlElement.new(:id, "searchtext")) add_action(CucumberLabel.new("submit"), ClickAction.new, AccessHtmlElement.new(:id, "submit")) add_action(CucumberLabel.new("Text Search Suggestion"), SendKeysAction.new, AccessHtmlElement.new(:id, "searchtext")) add_action(CucumberLabel.new("Suggestion List"), VerifyText.new, AccessHtmlElement.new(:id, "suggestList")) add_verify(CucumberLabel.new("Search Results"), SendKeysAndEnterAction.new, AccessHtmlElement.new(:id, "searchResults")) add_verify(CucumberLabel.new("No Results"), SendKeysAndEnterAction.new, AccessHtmlElement.new(:id, "noResults")) @@search_result_rows = AccessHtmlElement.new(:id, "searchResults") add_verify(CucumberLabel.new("Number of Search Result Rows"), VerifyXpathCount.new(@@search_result_rows), @@search_result_rows) add_verify(CucumberLabel.new("SearchResultMsg"), VerifyText.new, AccessHtmlElement.new(:id, "search-results-message")) add_verify(CucumberLabel.new("Search Result Count"), VerifyText.new, AccessHtmlElement.new(:id, "numberOfResults")) add_verify(CucumberLabel.new("Result Count"), VerifyText.new, AccessHtmlElement.new(:xpath, "//*[starts-with(@id,'ResultCount')]")) @@count_action = AccessHtmlElement.new(:xpath, ".//*[@id='suggestList']/li") add_verify(CucumberLabel.new("suggestion count"), VerifyXpathCount.new(@@count_action), @@count_action) add_verify(CucumberLabel.new("Group Search Result"), VerifyText.new, AccessHtmlElement.new(:css, ".searchGroupTitle.panel-heading")) add_action(CucumberLabel.new("Control - Text Search - From Date"), SendKeysAction.new, AccessHtmlElement.new(:id, "fromDateText")) add_action(CucumberLabel.new("Control - Text Search - To Date"), SendKeysAction.new, AccessHtmlElement.new(:id, "toDateText")) add_action(CucumberLabel.new("Control - Text Search - Apply"), ClickAction.new, AccessHtmlElement.new(:id, "custom-range-apply")) ###### End of Date Control ## add_action(CucumberLabel.new("Search Spinner"), ClickAction.new, AccessHtmlElement.new(:id, "searchSpinner")) ## Search result deatail #### add_verify(CucumberLabel.new("Medication - ascorbic acid tab"), VerifyText.new, AccessHtmlElement.new(:id, "mainModalLabel")) add_verify(CucumberLabel.new("Vaccine - CHOLERA, ORAL (HISTORICAL)"), VerifyText.new, AccessHtmlElement.new(:id, "mainModalLabel")) add_verify(CucumberLabel.new("Allergen - PENICILLIN"), VerifyText.new, AccessHtmlElement.new(:id, "mainModalLabel")) add_verify(CucumberLabel.new("EYE DISORDERS"), VerifyText.new, AccessHtmlElement.new(:id, "mainModalLabel")) add_verify(CucumberLabel.new("HDL"), VerifyText.new, AccessHtmlElement.new(:id, "mainModalLabel")) add_verify(CucumberLabel.new("Headache"), VerifyText.new, AccessHtmlElement.new(:id, "mainModalLabel")) add_verify(CucumberLabel.new("Snippest"), VerifyContainsText.new, AccessHtmlElement.new(:id, "ResultHighlightssubgroupItem0")) add_verify(CucumberLabel.new("Rad Order Status"), VerifyContainsText.new, AccessHtmlElement.new(:xpath, "//*[@id='modal-body']/descendant::div/div[10]/div[2]")) add_verify(CucumberLabel.new("Lab Order Status"), VerifyText.new, AccessHtmlElement.new(:xpath, "//*[@id='modal-body']/descendant::div/div[9]/div[2]")) end end class TextSearchContainerDrillDown < AccessBrowserV2 include Singleton def initialize super ## search result drill down ### add_action(CucumberLabel.new("Medication, Outpatient"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-MedicationOutpatient")) add_action(CucumberLabel.new("Immunization"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-Immunization")) add_action(CucumberLabel.new("Allergy/Adverse Reaction"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-AllergyAdverseReaction")) add_action(CucumberLabel.new("Laboratory"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-Laboratory")) add_action(CucumberLabel.new("Problem"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-Problem")) add_action(CucumberLabel.new("Radiology Report"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-RadiologyReport")) add_action(CucumberLabel.new("Progress Note"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-ProgressNote")) add_action(CucumberLabel.new("Administrative Note"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-AdministrativeNote")) add_action(CucumberLabel.new("Advance Directive"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-AdvanceDirective")) add_action(CucumberLabel.new("Clinical Procedure"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-ClinicalProcedure")) add_action(CucumberLabel.new("Consult Report"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-ConsultReport")) add_action(CucumberLabel.new("Consultation Note"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-ConsultationNoteProviderDocument")) add_action(CucumberLabel.new("Crisis Note"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-CrisisNote")) add_action(CucumberLabel.new("Discharge Summary"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-DischargeSummary")) add_action(CucumberLabel.new("Laboratory Report"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-LaboratoryReport")) add_action(CucumberLabel.new("Radiology Report"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-RadiologyReport")) add_action(CucumberLabel.new("Surgery Report"), ClickAction.new, AccessHtmlElement.new(:id, "result-group-title-SurgeryReport")) add_action(CucumberLabel.new("General Medicine Note"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-GENERALMEDICINENOTE-1")) add_action(CucumberLabel.new("Diabetes"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-DIABETES-1")) add_action(CucumberLabel.new("Administrative Note2"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-AdministrativeNote-1")) add_action(CucumberLabel.new("Advance Directive2"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-ADVANCEDIRECTIVE-1")) add_action(CucumberLabel.new("Col"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-COL-1")) add_action(CucumberLabel.new("Audiology Hearing Loss Consult"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-AUDIOLOGYHEARINGLOSSCONSULT-1")) add_action(CucumberLabel.new("Consultation Note Document"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-ConsultationNoteProviderDocument-1")) add_action(CucumberLabel.new("Crisis Note subgroup"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-CRISISNOTE-1")) add_action(CucumberLabel.new("Discharge Summary subgroup"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-DischargeSummary-1")) add_action(CucumberLabel.new("LR ELECTRON MICROSCOPY REPORT"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-LRELECTRONMICROSCOPYREPORT-1")) add_action(CucumberLabel.new("ANKLE 2 VIEWS"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-ANKLE2VIEWS-1")) add_action(CucumberLabel.new("ANESTHESIA REPORT"), ClickAction.new, AccessHtmlElement.new(:id, "result-subGroup-title-ANESTHESIAREPORT-1")) add_action(CucumberLabel.new("Sub Group List"), ClickAction.new, AccessHtmlElement.new(:id, "ResultDatesubgroupItem0")) add_action(CucumberLabel.new("Penicillin"), ClickAction.new, AccessHtmlElement.new(:xpath, "//div[contains(text(),'PENICILLIN')]")) add_action(CucumberLabel.new("Headache"), ClickAction.new, AccessHtmlElement.new(:xpath, "//div[contains(@class,'searchResultItem')]/descendant::div[contains(string(),'Headache')]")) add_action(CucumberLabel.new("Cholera"), ClickAction.new, AccessHtmlElement.new(:xpath, "//div[contains(text(),'CHOLERA')]")) #add_action(CucumberLabel.new("Urinalysis"), ClickAction.new, AccessHtmlElement.new(:xpath, "//div[contains(@class,'searchResultItem')]/descendant::div[contains(string(),'URINALYSIS')]")) add_action(CucumberLabel.new("Urinalysis"), ClickAction.new, AccessHtmlElement.new(:xpath, "//div[@data-uid='urn:va:order:C877:229:8856'] ")) add_action(CucumberLabel.new("Knee"), ClickAction.new, AccessHtmlElement.new(:xpath, "//*[@id='result-group-RadiologyReport']/div/div[6]")) add_action(CucumberLabel.new("HDL"), ClickAction.new, AccessHtmlElement.new(:xpath, "//div[contains(@class,'searchResultItem')]/descendant::div[contains(string(),'HDL')]")) add_action(CucumberLabel.new("Ascorbic Acid"), ClickAction.new, AccessHtmlElement.new(:xpath, "//div[contains(@class,'searchResultItem')]/descendant::div[contains(string(),'ASCORBIC')]")) add_action(CucumberLabel.new("Allergies"), ClickAction.new, AccessHtmlElement.new(:xpath, "//*[@id='result-subGroup-DIABETES-1']/div/div[2]")) add_action(CucumberLabel.new("bundle branch block"), ClickAction.new, AccessHtmlElement.new(:xpath, "//*[@id='result-subGroup-DIABETES-1']/div/div[2]")) add_action(CucumberLabel.new("Chocolate"), ClickAction.new, AccessHtmlElement.new(:xpath, "//mark[contains(text(),'CHOCOLATE')]")) end end def group_search_results(grouped_list, table) matched = false table.rows.each do |item, k| grouped_list.each do |grouped_item| #p "item is + #{grouped_item.text}, #{item}" if grouped_item.text == item.upcase matched = true break else matched = false end #end of if end #end of grouped p "could not match cucumber_row: #{item}" unless matched #expect(matched).to be_true end #end of table return matched end #end of def def search_text_and_clicking(search_value) con = TextSearchContainer.instance driver = TestSupport.driver #con.add_action(CucumberLabel.new("Search Spinner"), ClickAction.new, AccessHtmlElement.new(:id, "searchSpinner")) expect(con.wait_until_element_present("Text Search Field", DefaultLogin.wait_time)).to be_true, "text search field did not display" expect(con.perform_action("Text Search Field", search_value)).to be_true, "text search field did not display" con.wait_until_element_present("Search Spinner") wait = Selenium::WebDriver::Wait.new(:timeout => DefaultTiming.default_table_row_load_time) # seconds # wait until list opens wait.until { driver.find_element(:id, "searchSpinner").attribute("style").strip =="display: none;" } # wait until specific list element is NOT con.wait_until_action_element_visible("Search Results", 70) end def search_result_message(search_value, count) con = TextSearchContainer.instance driver = TestSupport.driver expected_msg = "#{count} results" expect(con.perform_verification("SearchResultMsg", expected_msg)).to be_true end def search_text(search_value) con = TextSearchContainer.instance con.perform_action("Text Search Suggestion", search_value) end def search_text_click_submit(search_value) con = TextSearchContainer.instance expect(con.perform_action("Text Search Suggestion", search_value)).to be_true, "Not able to enter text in the search field" expect(con.perform_action("submit", "")).to be_true, "was not able to click on the submit button" end def search_suggetions_count(search_value, expected_num) con = TextSearchContainer.instance driver = TestSupport.driver num_seconds = 30 #p expected_num p "suggestion count expected #{expected_num}" con.wait_until_xpath_count("suggestion count", expected_num, num_seconds) p "wait completed" expect(con.perform_verification("suggestion count", expected_num, 10)).to be_true, "" end Given(/^user type text term and the page contains total items and search results$/) do |table| table.rows.each do |text, total_items| search_text_and_clicking(text) search_result_message(text, total_items) end end Given(/^user searches for "(.*?)"$/) do |text_term| search_text_and_clicking(text_term) end def check_group_results(table) driver = TestSupport.driver browser_elements = driver.find_elements(:xpath, "//*[@id='searchResults']/descendant::h4") matched = group_search_results(browser_elements, table) end Then(/^text search result contains$/) do |table| driver = TestSupport.driver con = TextSearchContainer.instance matched =false con.wait_until_action_element_visible("Search Results", 70) wait = Selenium::WebDriver::Wait.new(:timeout => DefaultLogin.wait_time) wait.until { check_group_results table } end Then(/^sub grouped search result for "(.*?)" contains$/) do |sub_group_category, table| con = TextSearchContainerDrillDown.instance driver = TestSupport.driver matched =false case sub_group_category when 'Headache' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-HeadacheICD9CM7840-1']/descendant::div") when 'General Medicine Note' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-GENERALMEDICINENOTE-1']/descendant::div") when 'Diabetes' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-DIABETES-1']/descendant::div") when 'Administrative Note2' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-AdministrativeNote-1']/descendant::div") when 'Advance Directive2' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-ADVANCEDIRECTIVE-1']/descendant::div") when 'Col' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-COL-1']/descendant::div") when 'Audiology Hearing Loss Consult' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-AUDIOLOGYHEARINGLOSSCONSULT-1']/descendant::div") when 'Consultation Note Document' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-ConsultationNoteProviderDocument-1']/descendant::div") when 'Crisis Note subgroup' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-CRISISNOTE-1']/descendant::div") when 'Discharge Summary subgroup' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-DischargeSummary-1']/descendant::div") when 'LR ELECTRON MICROSCOPY REPORT' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-LRELECTRONMICROSCOPYREPORT-1']/descendant::div") when 'ANKLE 2 VIEWS' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-ANKLE2VIEWS-1']/descendant::div") when 'ANESTHESIA REPORT' expect(con.wait_until_element_present("Sub Group List", 60)).to be_true, "Sub Group List did not display" browser_elements_list = driver.find_elements(:xpath, "//*[@id='result-subGroup-ANESTHESIAREPORT-1']/descendant::div") else fail "**** No function found! Check your script ****" end #end for case con = VerifyTableValue.new matched = con.verify_name_value(browser_elements_list, table) expect(matched).to be_true, "could not match" end When(/^from the coversheet the user clicks on "([^"]*)"$/) do |element| aa = TextSearchContainer.instance driver = TestSupport.driver aa.wait_until_action_element_visible(element, 60) expect(aa.static_dom_element_exists?(element)).to be_true, "Record Search Button did not display" expect(aa.perform_action(element, "")).to be_true, "was not able to click on the button" end Given(/^user type text term "(.*?)" in the search text box$/) do |search_value| con = TextSearchContainer.instance con.perform_action("Text Search Field", search_value) end Then(/^search result displays "(.*?)" search results$/) do |total_no_search_results| con = TextSearchContainer.instance expect(con.static_dom_element_exists?("Search Result Count")).to be_true expect(con.perform_verification("Search Result Count", total_no_search_results)).to be_true end Then(/^the user clicks one of the search result "([^"]*)"$/) do |element| driver = TestSupport.driver aa = TextSearchContainerDrillDown.instance aa.wait_until_action_element_visible(element, 60) expect(aa.static_dom_element_exists?(element)).to be_true expect(aa.perform_action(element, "")).to be_true, "element did not display" end When(/^the user enters "(.*?)" in the "(.*?)" control$/) do |input_text, control_name| aa = TextSearchContainer.instance control = "Control - #{control_name}" p "control is #{control}" expect(aa.perform_action(control, input_text)).to be_true, "element did not display" end Then(/^user type <text> term and the page displays total no of suggestions "(.*?)"$/) do |arg1, table| table.rows.each do |text, total_items| p "search #{text}" search_text(text) search_suggetions_count(text, total_items) end end Then(/^the following date time filter option should be displayed$/) do |table| driver = TestSupport.driver matched =false browser_elements = driver.find_elements(:xpath, "//*[@id='globalDate-region']/descendant::button") p browser_elements.length #p browser_elements.text.strip matched = group_search_results(browser_elements, table) expect(matched).to be_true end Then(/^the "(.*?)" contains$/) do |name, table| driver = TestSupport.driver con = Documents.instance browser_elements_list = driver.find_elements(:xpath, "//*[@id='modal-body']/descendant::div") p browser_elements_list.length browser_elements_list.each do |label_in_browser| p label_in_browser.text.strip end matched = false con = VerifyTableValue.new matched = con.verify_name_value(browser_elements_list, table) expect(matched).to be_true end def wait_until_numberofresults(number_of_results) web_driver = TestSupport.driver wait = Selenium::WebDriver::Wait.new(:timeout => DefaultLogin.wait_time) p "numberOfResults #{web_driver.execute_script("return window.document.getElementById('numberOfResults').innerHTML")}" wait.until { web_driver.execute_script("return window.document.getElementById('numberOfResults').innerHTML") == number_of_results } p "not hanging here" end Then(/^search result header displays (\d+) number of results$/) do |arg1| wait_until_numberofresults arg1 end Then(/^the user sees the search text "(.*?)" in yellow$/) do |search_text| driver = TestSupport.driver matched = false text_color = "" browser_elements_list = driver.find_elements(:css, ".cpe-search-term-match") p browser_elements_list.length browser_elements_list.each do | element| text_color = element.css_value("background-color") #check only rgb value in string since alpha value is inconsistent across build environments if text_color[0, 20] == "rgba(255, 255, 0, 0." matched = true else matched = false end end expect(matched).to be_true, "color in browser: #{text_color} found in feature file yellow" end Then(/^Current Status for "(.*?)" is "(.*?)"$/) do |order_type, order_status| aa = TextSearchContainer.instance order_type_status = order_type + " " + "Order Status" aa.wait_until_element_present(order_type_status, 60) expect(aa.static_dom_element_exists?(order_type_status)).to be_true, "element did not exists" expect(aa.perform_verification(order_type_status, order_status)).to be_true, "Order status is #{order_type_status}" end Then(/^the following subgroups data are not loaded$/) do |table| driver = TestSupport.driver table.rows.each do | rows_value | element_id = "result-subGroup-" + rows_value[0] + "-1" #element_id = "result-subGroup" matched = driver.find_element(:id , element_id).displayed? expect(!matched).to be_true , "#{element_id} is loaded" end end Then(/^user searches for "(.*?)" with no suggestion$/) do |text| driver = TestSupport.driver aa = TextSearchContainer.instance wait = Selenium::WebDriver::Wait.new(:timeout => 60) search_text(text) element_id = "noResults" wait.until { (driver.find_element(:id, element_id).attribute("style").strip =="display: none; padding-left: 10px;" || driver.find_element(:id, element_id).attribute("style").strip =="padding-left: 10px; display: none;") } expect((driver.find_element(:id, element_id).attribute("style").strip =="display: none; padding-left: 10px;" || driver.find_element(:id, element_id).attribute("style").strip =="padding-left: 10px; display: none;")).to be_true end Then(/^user searches for "(.*?)" with no duplicates in the results dropdown$/) do |text| driver = TestSupport.driver wait = Selenium::WebDriver::Wait.new(:timeout => 60) suggest = Array.new(16) search_text(text) wait.until { driver.find_element(:id, "suggestList").attribute("style").strip =="display: block;" } #Problems with <span> elements (ex: <span id>, <span id=""">). NOT FINNISHED! for i in 0..15 #p "#{i}" word = "" driver.find_elements(:xpath, "//li[@id='SuggestItem#{i}']/a/span").each { |td| word = word + td.text } #p word suggest[i] = word end #p "#{suggest}" expect(suggest.uniq! == nil).to be_true end Then(/^the modal contains highlighted "(.*?)"$/) do |searchterm| driver = TestSupport.driver no_elem = Array.new expect(driver.find_element(:xpath, "//*[@id='modal-body']//mark[@class='cpe-search-term-match']").text == searchterm) end Then(/^user searches for "(.*?)" and verifies suggestions$/) do |text, table| driver = TestSupport.driver wait = Selenium::WebDriver::Wait.new(:timeout => 60) suggest = Array.new search_text(text) wait.until { driver.find_element(:id, "suggestList").attribute("style").strip =="display: block;" } suggestions = driver.find_elements(:xpath, "//ul[@id='suggestList']/li") for i in 0..suggestions.length-1 word = "" driver.find_elements(:xpath, "//li[@id='SuggestItem#{i}']/a/span").each { |td| word = word + td.text } suggest[i] = word end j = 1 table.rows.each do | rows_value | #p rows_value[0] #p suggest[j] expect(rows_value[0] == suggest[j]).to be_true j += 1 end end
class AddStatusAndColorToPieces < ActiveRecord::Migration[5.2] def change add_column :pieces, :status, :boolean add_column :pieces, :color, :string end end
module Api class ActivitiesController < ApiController def index @activities = current_user.own_activities.includes(:user, :picture).page 1 end def destroy @activity = Activity.find(params[:id]) @activity.destroy render json: @activity end def update @activity = Activity.find(params[:id]) @activity.update(viewed: true) render json: @activity end private def activity_params params.require(activity).permit(:viewed) end end end
feature 'authentication' do scenario 'a user can sign in' do visit('/') click_button 'Sign up' fill_in('email', :with => 'carlo@fonte.com') fill_in('password', :with => '1234') fill_in('name', :with => 'carlo') fill_in('username', :with => 'carlitos') click_button 'Submit' expect(page).to have_content 'Hi carlo, share a post with your friends:' end scenario 'an error is printed when password doesnt match with email' do visit('/') fill_in('email', :with => 'dani@bortnik.com') fill_in('password', :with => 'wrongpassword') click_button 'Submit' expect(page).not_to have_content 'Hi dani, share a post with your friends:' expect(page).to have_content 'Something does not match, please try again:' end scenario 'an error is printed when email is wrong' do visit('/') fill_in('email', :with => 'dani@bortnikkkkk.com') fill_in('password', :with => '1234') click_button 'Submit' expect(page).not_to have_content 'Hi dani, share a post with your friends:' expect(page).to have_content 'Something does not match, please try again:' end scenario 'user can sign out' do visit('/') fill_in('email', :with => 'carlo@fonte.com') fill_in('password', :with => '1234') click_button 'Submit' click_button 'Sign out' expect(page).to have_content 'You have signed out' end end
module Synchronisable module Input # Provides a set of helper methods # to describe user input. # # @api private # # @see Synchronisable::Input::Descriptor class Descriptor attr_reader :data def initialize(data) @data = data end def empty? @data.blank? end def params? @data.is_a?(Hash) end def remote_id? @data.is_a?(String) end def local_id? @data.is_a?(Integer) end def array_of_ids? enumerable? && ( first_element.is_a?(String) || first_element.is_a?(Integer) ) end def element_class first_element.try(:class) end private def first_element @data.try(:first) end def enumerable? @data.is_a?(Enumerable) end end end end
class Question < ActiveRecord::Base attr_accessor :tweet_it belongs_to :category belongs_to :user # This will establish a `has_many` association with answers. This assumes # that your answer model has a `question_id` integer field that references # the question. with has_many `answers` must be plural (Rails convention). # We must pass a `dependent` option to maintain data integrity. The possible # values you can give it are: :destroy or :nullify # With :destroy: if you delete a question it will delete all associated answers # With :nullify: if you delete a question it will update the `question_id` NULL # for all associated records (they won't get deleted) has_many :answers, dependent: :destroy # This enables us to access all the comments created for all the question's # answers. This generates a single SQL statement with `INNER JOIN` to # accompolish it has_many :comments, through: :answers has_many :likes, dependent: :destroy has_many :users, through: :likes has_many :favourites, dependent: :destroy has_many :favrouting_users, through: :favourites, source: :user has_many :taggings, dependent: :destroy has_many :tags, through: :taggings has_many :votes, dependent: :destroy has_many :voting_users, through: :votes, source: :user # this will fail validations (so it won't create or save) if the title is # not provided validates :title, presence: true, uniqueness: { case_sensitive: false }, length: {minimum: 3, maximum: 255} # DSL: Domain Specific Language # the code we use in here is completely valid Ruby code but the method naming # and arguments are specific to ActiveRecord so we call this an ActiveRecord # DSL validates(:body, {uniqueness: {message: "must be unique!"}}) # this validates that the combination of the title and body is unique. Which # means the title doesn't have to be unique by itself and the body doesn't # have to be unique by itself. However, the combination of the two fields # must be unique # validates :title, uniqueness: {scope: :body} validates :view_count, numericality: {greater_than_or_equal_to: 0} # validates :email, # format: { with: /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i } # This is using custom validation method. We must make sure that `no_monkey` # is a method available for our class. The method can be public or private # It's more likely we will have it a private method because we don't need # to use it outside this class. validate :no_monkey after_initialize :set_defaults before_save :capitalize_title # scope :recent, lambda {|x| order("created_at DESC").limit(x) } def self.recent(number = 5) order("created_at DESC").limit(number) end def self.popular where("view_count > 10") end # Wildcard search by title or body # ordered by view_count in a descending order def self.search(term) where(["title ILIKE ? OR body ILIKE ?", "%#{term}%", "%#{term}%"]). order("view_count DESC") end def category_name category.name if category end # delegate :full_name, to: :user, prefix: true, allow_nil: true def user_full_name user.full_name if user end def like_for(user) likes.find_by_user_id user end def fav_for(user) favourites.find_by_user_id user end def vote_for(user) votes.find_by_user_id user end def vote_result votes.up_count - votes.down_count end private def set_defaults self.view_count ||= 0 end def capitalize_title self.title.capitalize! end def no_monkey if title && title.downcase.include?("monkey") errors.add(:title, "No monkey!!") end end end
ActiveAdmin.register Caracteristica do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # permit_params :segmento_id, :tipo, :nombre # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if resource.something? # permitted # end form do |f| f.inputs "Details" do f.input :segmento_id, :as => :select, :member_label => :nombre, :collection => Segmento.all f.input :tipo, :as => :select, :member_label => :nombre, :member_value => :nombres, :collection => TipoCaract.all f.input :nombre end f.actions end end
class Genre < ActiveHash::Base self.data = [ { id: 1, name: '---' }, { id: 2, name: '打撃' }, { id: 3, name: '投球' }, { id: 4, name: '守備' }, { id: 5, name: '送球' }, { id: 6, name: '走塁' }, { id: 7, name: '配球' }, { id: 8, name: '練習方法' }, { id: 9, name: '指導方法' }, { id: 10, name: '食事・サプリメント' }, { id: 11, name: 'その他' } ] end
require 'test_helper' class CarreraMateriaControllerTest < ActionDispatch::IntegrationTest setup do @carrera_materium = carrera_materia(:one) end test "should get index" do get carrera_materia_url assert_response :success end test "should get new" do get new_carrera_materium_url assert_response :success end test "should create carrera_materium" do assert_difference('CarreraMaterium.count') do post carrera_materia_url, params: { carrera_materium: { carrera_id: @carrera_materium.carrera_id, materia_id: @carrera_materium.materia_id } } end assert_redirected_to carrera_materium_url(CarreraMaterium.last) end test "should show carrera_materium" do get carrera_materium_url(@carrera_materium) assert_response :success end test "should get edit" do get edit_carrera_materium_url(@carrera_materium) assert_response :success end test "should update carrera_materium" do patch carrera_materium_url(@carrera_materium), params: { carrera_materium: { carrera_id: @carrera_materium.carrera_id, materia_id: @carrera_materium.materia_id } } assert_redirected_to carrera_materium_url(@carrera_materium) end test "should destroy carrera_materium" do assert_difference('CarreraMaterium.count', -1) do delete carrera_materium_url(@carrera_materium) end assert_redirected_to carrera_materia_url end end
class Retailer < ActiveRecord::Base has_many :deals has_and_belongs_to_many :categories validates :name, presence: true validates :host_url, presence: true validates :brief_description, presence: true mount_uploader :favicon, PictureUploader mount_uploader :logo, PictureUploader mount_uploader :cover, PictureUploader extend FriendlyId friendly_id :name, use: :slugged acts_as_xlsx def self.to_csv CSV.generate do |csv| csv << column_names all.each do |item| csv << item.attributes.values_at(*column_names) end end end def self.import(file) CSV.foreach(file.path, headers: true) do |row| item = find_by_id(row["id"]) || new item.attributes = row.to_hash.slice(*self.column_names) next if item.name.nil? || item.host_url.nil? || item.brief_description.nil? item.save! item.update_attributes(category_ids: row["category_ids"]) if row["category_ids"].present? end end end
class Hash def slice(*args) sliced_value = {} args.each do |arg| sliced_value[arg] = fetch(arg) end sliced_value end end
class RenameSyncsToSyncSessions < ActiveRecord::Migration def self.up remove_index :syncs, :user_id rename_table :syncs, :sync_sessions add_index :sync_sessions, :user_id remove_index :events, :sync_id rename_column :events, :sync_id, :sync_session_id add_index :events, :sync_session_id end def self.down remove_index :events, :sync_session_id rename_column :events, :sync_session_id, :sync_id add_index :events, :sync_id remove_index :sync_sessions, :user_id rename_table :sync_sessions, :syncs add_index :syncs, :user_id end end
class Product < ApplicationRecord has_many :orders_products has_many :orders, through: :orders_products validates :quantity, numericality: { only_integer: true, greater_than_or_equal_to: 0 } default_scope :in_inventory, -> { where("quantity > :qty", qty: 0) } scope :not_expired, -> { where expired: false } scope :order_name, -> { order(:name) } # def self.not_expired_in_inventory # in_inventory.not_expired # end end
require 'formula' class Ltl2ba < Formula homepage 'http://www.lsv.ens-cachan.fr/~gastin/ltl2ba/' url 'http://www.lsv.ens-cachan.fr/~gastin/ltl2ba/ltl2ba-1.1.tar.gz' sha256 'a66bf05bc3fd030f19fd0114623d263870d864793b1b0a2ccf6ab6a40e7be09b' def install system "make" bin.install "ltl2ba" end end
require "rails_helper" feature "user views home page" do scenario "and visits about page" do visit root_path click_on "About" expect(page).to have_content "About" end end
Rails.application.routes.draw do root "bookmarks#index" get "signup" => "signup#new" post "signup" => "signup#create" get "login" => "sessions#new" post "login" => "sessions#create" get "logout" => "sessions#destroy" get "dashboard" => "bookmarks#index" resources :bookmarks, except: [:index] resources :sites, only: [:index, :destroy] resources :tags, only: [:index, :destroy] end
require "faker" require_relative "producto" class GeneradorProductos def self.generar #logica para crear productos producto_nuevo = Producto.new producto_nuevo.nombre = generar_nombre(producto_nuevo) producto_nuevo.precio = rand(1000..50000) producto_nuevo.codigo = Faker::Barcode.ean producto_nuevo.marca = obtener_marca producto_nuevo.presentacion = Faker::Food.measurement #producto_nuevo.categoria = obtener_categoria return producto_nuevo end private def self.generar_nombre(producto) case rand(0..2) when 0 producto.categoria = "frutas" return Faker::Food.fruits when 1 producto.categoria = "platos" return Faker::Food.dish when 2 producto.categoria = "vegetales" return Faker::Food.vegetables end end def self.obtener_marca marcas = ["a", "b", "c", "d", "e", "f"] return marcas.sample #obntener marca al azar end # def obtener_categoria # #obtener categoria # end end
require_relative "spider" module Crawler class Bot SPIDERS_NUMBER = 5 def self.start spiders = [] SPIDERS_NUMBER.times do |i| spiders << Spider.supervise({number:i}) end sleep end end end
class Website < ApplicationRecord has_many :tag_contents def self.search(params) keyword = params['keyword'] || '' order = params['order'] || 'id DESC' Website.where('url like ?', "%#{keyword}%").order(order) end end
require 'csv' require 'json' require 'open-uri' require 'trello' def configure_trello options Trello.configure do |config| config.developer_public_key = options[:key] config.member_token = options[:token] end end module Datamine::CLI desc 'Manipulate Trello Boards' command :trello do |c| c.desc 'Trello API key' c.flag :key c.desc 'Trello API token' c.flag :token c.desc 'Default Trello Board' c.flag :board_id # Default action is to list all available boards c.default_desc 'Display available boards' c.action do |global_options,options,args| configure_trello options Trello::Board.all.each do |b| info = [b.id, "\t", b.name] # Mark archived boards info << [" (closed)"] if b.closed puts info.join end end c.desc 'Display lists on board' c.command :lists do |s| s.action do |global_options,options,args| configure_trello options Trello::Board.find(options[:board_id]).lists.each {|l| puts [l.id, "\t", l.name].join} end end c.desc 'Archive all cards on board' c.command :archive do |s| s.action do |global_options,options,args| configure_trello options Trello::Board.find(options[:board_id]).cards.map{|c| c.close!} end end c.desc 'Purge cards from board (DANGER this is permanent)' c.command :purge do |s| s.action do |global_options,options,args| configure_trello options Trello::Board.find(options[:board_id]).cards.map{|c| c.delete} end end c.desc 'Export board as JSON' c.command :export do |s| s.action do |global_options,options,args| configure_trello options # From: # http://www.shesek.info/general/automatically-backup-trello-lists-cards-and-other-data backup_url = "https://api.trello.com/1/boards/#{options[:board_id]}?key=#{options[:key]}&token=#{options[:token]}&actions=all&actions_limit=1000&cards=all&lists=all&members=all&member_fields=all&checklists=all&fields=all" backup_json = JSON.parse(open(backup_url).read) puts JSON.pretty_generate(backup_json) end end c.desc 'Add cards to a list on the board' c.arg_name 'json_file' c.command :add do |s| s.desc 'The name or id of the list to which cards should be added' s.arg_name 'string' s.flag :list s.desc 'The first ticket in the list to post' s.arg_name 'integer' s.default_value 0 s.flag :start s.desc 'The last ticket in the list to post' s.arg_name 'integer' s.default_value -1 s.flag :stop s.action do |global_options,options,args| configure_trello options options[:start] = options[:start].to_i options[:stop] = options[:stop].to_i board = Trello::Board.find(options[:board_id]) list_hash = board.lists.map{|l| {l.name => l.id}}.reduce Hash.new, :merge target_list = list_hash[options[:list]] || list_hash[list_hash.key(options[:list])] raise 'You must target this command at an existing list!' if target_list.nil? issue_file = args.first raise 'You must provide a valid json file' if issue_file.nil? || (not File.exist?(issue_file)) tickets = JSON.parse(File.read(issue_file)) options[:stop] = tickets.length if options[:stop] == -1 tickets = tickets[ options[:start], options[:stop] ] # Ensure we find archived cards. existing_cards = board.cards({:filter => :all}) tickets.each do |t| card = { :name => "(#{t['key']}) #{t['summary']}", :description => "# #{t['url']}\n---\n#{t['description']}", } existing_card = existing_cards.find {|e| e.name == card[:name]} unless existing_card.nil? if existing_card.closed? existing_card.closed = false existing_card.list_id = target_list existing_card.save $stderr.puts "Retrieved archived card for #{t['key']}." else $stderr.puts "Issue #{t['key']} is already on the board." end next end begin Trello::Card.create({:name => card[:name], :list_id => target_list, :desc => card[:description]}) rescue Trello::Error => e if e.to_s =~ /^invalid value for desc/ # Sometimes, Trello can't handle the full description. Retry # using just the first line, which is a URL link to the Redmine # issue. $stderr.puts "Issue rejected. Retrying" card[:description] = card[:description].split[0] retry else raise e end end end $stderr.puts "There are now #{board.cards.length} cards on the board." end end c.desc 'Add users to board' c.arg_name 'csv_file' c.command :add_users do |s| s.action do |global_options,options,args| configure_trello options require 'addressable/uri' csv_file = args.first raise 'You must provide a CSV file containing usernames and emails' if csv_file.nil? uri = Addressable::URI.new auth_params = options.select{|k, v| [:key, :token].include? k} CSV.table(csv_file).each do |row| uri.query_values = { :fullName => row[:fullname], :email => row[:email] }.update auth_params puts `curl -H 'Accept: application/json' -X PUT --data '#{uri.query}' https://api.trello.com/1/board/#{options[:board_id]}/members` end end end end end
require 'spec_helper' describe Fudge::Tasks::Cucumber do it { is_expected.to be_registered_as :cucumber } describe '#run' do it 'turns on color if not specified' do expect(subject).to run_command /--color/ end it 'turns off color if specified' do expect(described_class.new(:color => false)).not_to run_command /--color/ end it 'appends any arguments passed in' do task = described_class.new('foobar', :color => false) expect(task).to run_command 'cucumber foobar' end it 'should default the arguments to spec/' do expect(described_class.new(:color => false)).to run_command 'cucumber features/' end end it_should_behave_like 'bundle aware' end
class AddPostIdAndLabelIdToLabeledPosts < ActiveRecord::Migration def change add_column :labelled_posts, :label_id, :integer add_column :labelled_posts, :post_id, :integer end end
module GeneratorsCore # some_entity def underscore_name singular_name.underscore end # some-entity def dash_name underscore_name.gsub '_', '-' end # SomeEntity def entity_name singular_name.camelcase end # someEntity def lowercase_entity_name singular_name.camelize(:lower) end # Some Entity def human_name underscore_name.gsub('_', ' ').titleize end # some_entities def plural_underscore_name name.underscore.pluralize end # some-entities def plural_dash_name plural_underscore_name.gsub '_', '-' end # SomeEntities def plural_entity_name name.camelcase.pluralize end # someEntities def plural_lowercase_entity_name name.camelcase(:lower).pluralize end # Some Entity def plural_human_name plural_underscore_name.gsub('_', ' ').titleize end def controller_file_name "app/controllers/api/v1/#{name.pluralize.downcase}_controller.rb" end def response_file_name(file_name) "app/views/api/v1/#{plural_underscore_name}/#{file_name}.json.jbuilder" end def view_model_file_name(view_model_name) "app/javascript/view_models/#{plural_underscore_name}/#{view_model_name}.vue" end def link_tag @config.dig('options', 'view_models', 'link_tag') || 'router-link' end def controller_name "#{plural_entity_name}Controller" end def mixins_list @config['generate']['mixins'] ? @config['generate']['mixins'].keys : [] end def view_models_list @config['generate']['view_models'].keys end def ensure_directory(file) dirname = File.dirname(file) FileUtils.mkdir_p(dirname) unless File.directory?(dirname) end def templates_path 'lib/generators/entity/templates' end def template_exists?(name) File.exist? "#{templates_path}/#{name}" end end
class ValidateSuite def validate_post_suite(suite_params) errors = [] params = JSON.parse(suite_params.to_json) return { error: "Deve possuir um JSON" } if params == {} or params == "{}" or params.nil? return { error: "Deve possuir o campo Nome" } unless params.include?("nome") name = params["nome"] if name.nil? errors << { error: "Nome não pode ser nulo" } elsif name.class != String errors << { error: "Nome deve ser string" } elsif name.empty? errors << { error: "Nome não pode ser em branco" } elsif name.length < 3 or name.length > 200 errors << { error: "Nome deve conter entre 3 e 200 caracteres" } end errors end def validate_edit_suite(suite_params) errors = [] params = JSON.parse(suite_params.to_json) return { error: "Deve possuir um JSON" } if params == {} or params == "{}" or params.nil? return { error: "Deve possuir o campo Nome" } unless params.include?("nome") name = params["nome"] if name.nil? errors << { error: "Nome não pode ser nulo" } elsif name.class != String errors << { error: "Nome deve ser string" } elsif name.empty? errors << { error: "Nome não pode ser em branco" } elsif name.length < 3 or name.length > 200 errors << { error: "Nome deve conter entre 3 e 200 caracteres" } end errors end def unique_value(error) { error: error[:nome][0] } end end
class Show < ApplicationRecord has_many :user_shows has_many :users, through: :shows has_many :seasons has_many :episodes, through: :seasons validates :description, uniqueness: true end
FactoryBot.define do factory :commodity do name { Faker.name } description { 'description' } category_id { 2 } state_id { 2 } postage_id { 2 } area_id { 1 } estimate_id { 2 } price { 8888 } after(:build) do |commodity| commodity.image.attach(io: File.open('public/images/test_image.png'), filename: 'test_image.png') end association :user end end
describe 'puppler init command' do it "runs without errors" do status = puppler 'init', '--package-name', 'foobar' expect(status).to be_truthy end %w[rules install control source/format].each do |fname| it "creates file debian/#{fname}" do file_path = workdir.join("debian", fname) expect(File).to exist(file_path) end end it "debian/install has expected content" do expect(File.read(workdir.join("debian/install"))).to include("bundles/*.bundle /usr/share/puppet/foobar/") end end
class Api::V1::LinksController < ApplicationController def index @links = Link.all render json: @links end def update @link = Link.find(params[:id]) @link.update(link_params) if @link.save render json: @link else render json: {errors: @link.errors.full_messages}, status: 422 end end private def link_params params.permit(:title, :url, :goal_id) end end
module FeatureHelper def login(the_user) visit new_user_session_path fill_in 'Email', with: the_user.email fill_in 'Password', with: the_user.password click_on 'Sign in' expect(page).to have_text 'My clients' expect(page).to have_current_path(root_path) end def add_client(the_client) visit new_client_path fill_in 'First name', with: the_client.first_name fill_in 'Last name', with: the_client.last_name fill_in 'Phone number', with: the_client.phone_number fill_in 'Notes', with: the_client['notes'] click_on 'Save new client' expect(page).to have_content('Manage client') end def add_template(the_template) visit new_template_path fill_in 'Template name', with: the_template.title fill_in 'Template', with: the_template.body click_on 'Save template' expect(page).to have_current_path(templates_path) end def wait_for(reason, timeout: Capybara.default_max_wait_time) Timeout.timeout(timeout) do loop do return_value = yield break return_value if return_value sleep 0.1 end end rescue Timeout::Error fail "Timed out waiting for #{reason}" end def xstep(title) puts "PENDING STEP SKIPPED: #{title}" if ENV['LOUD_TESTS'] end def step(title) puts "STEP: #{title}" if ENV['LOUD_TESTS'] yield end def save_and_open_preview file_preview_url = file_preview_url(host: 'localhost:3000', file: save_page) `open #{file_preview_url}` end def wut # if you want to see CSS with this command, see file_previews_controller.rb save_and_open_preview end def table_contents(selector, header: true) [].tap do |contents| within(selector) do if header all('thead tr').map do |tr| contents << tr.all('th').map(&:text) end end all('tbody tr').map do |tr| contents << tr.all('th, td').map(&:text) end end end end def on_page(page_title) expect(page.title).to eq page_title puts "PAGE: #{page_title}" if ENV['LOUD_TESTS'] # Protection against missed i18n links expect(page).not_to have_text('{') yield end end
require_relative "answers" require "colorize" class Main attr_accessor :answers def initialize @answers = Answers.new welcome end def e_menu puts "Have a wonderful day!" exit end # def user_add # puts "Please enter your suggestion" # @sugg = gets.strip # # puts "Is this a good, bad or neutral suggestion?" # # col = gets.strip.downcase # arr.new{name: } = @sugg # end def welcome puts "Welcome to the Magic Eight Ball!" puts "To exit at any time type 'exit'" puts "Press E if you want to suggest an answer for the 8 ball" puts "Ask me a question!" question = gets.strip.downcase answer = @answers.all.sample if question == "exit" e_menu # if question == "e" # user_add elsif answer[:color] === "red" puts "#{answer[:response]}".colorize(:red) elsif answer[:color] === "green" puts "#{answer[:response]}".colorize(:green) else puts "#{answer[:response]}".colorize(:yellow) end welcome end end Main.new
# frozen_string_literal: true module GraphQL VERSION = "1.9.9" end
class Segmento < ActiveRecord::Base has_many :caracteristicas, dependent: :destroy end
class UserMailer < ApplicationMailer default from: 'shyam.shinde@neosofttech.com' def welcome_email(user) @user = user mail(to: @user.email, subject: 'Welcome to My Awesome Site') end end
class CreateCampaigns < ActiveRecord::Migration[5.0] def change create_table :campaigns do |t| t.references :creator, foreign_key: true t.string :name t.string :description t.string :kickstarter_url t.string :sidekick_url t.string :currency t.integer :funding_goal t.integer :total_backers_count t.float :total_pledges_amount t.date :start_date t.date :end_date t.integer :running_days_count t.string :picture_url t.timestamps end end end
class StartViewController < UIViewController def viewDidLoad self.title = "Magic Field" view.userInteractionEnabled = true drawBackgroundImage drawStartScreenWindow drawWelcomeMessage drawPlayerInputs drawPlayerOneManaButtons drawPlayerTwoManaButtons createStartButton end private def drawBackgroundImage @backgroundImage = UIImageView.alloc.initWithImage UIImage.imageNamed('field.png') view.addSubview @backgroundImage end def drawStartScreenWindow decorative_box = UIImage.imageNamed('decorative-box.png') @startScreenWindow = UIImageView.alloc.initWithImage(decorative_box) @startScreenWindow.frame = [[2, 226], decorative_box.size] view.addSubview @startScreenWindow end def drawWelcomeMessage @welcome_message = createLabel("Welcome To Magic Field", { offset: [190, 345], fontSize: 40, font: "Booter - Five Zero", color: UIColor.whiteColor, shadow: true }) view.addSubview @welcome_message end def drawPlayerInputs @p1Name = createPlayerInput({ placeholder: "Player One", offset: [189, 427], }) @p2Name = createPlayerInput({ placeholder: "Player Two", offset: [189, 517], }) # Dev placeholders @p1Name.text = "Dayton" @p2Name.text = "Mikey" view.addSubview @p1Name view.addSubview @p2Name end def drawPlayerOneManaButtons redManaButton = MagicField::ManaButton.new "red" view.addSubview redManaButton.button end def drawPlayerTwoManaButtons end def createStartButton @startButton = UIButton.buttonWithType UIButtonTypeRoundedRect @startButton.frame = [[460, 600], [100, 37]] @startButton.setTitle("Start", forState:UIControlStateNormal) @startButton.addTarget(self, action:"startGame", forControlEvents:UIControlEventTouchUpInside) view.addSubview @startButton end def startGame if thereAreTwoPlayers? @p1Name.resignFirstResponder @p2Name.resignFirstResponder @battlefieldView = BattlefieldViewController.alloc.init @battlefieldView.start(@p1Name.text, @p2Name.text) self.navigationController.pushViewController(@battlefieldView, animated:true) else alert "You need two players to play" end end def textFieldShouldReturn(textField) textField.resignFirstResponder true end def textFieldShouldEndEditing(textField) textField.resignFirstResponder true end def createPlayerInput(options) defaults = { dimensions: [390, 45], font: UIFont.systemFontOfSize(30), delegate: self } settings = defaults.merge! options textField = createTextField(settings) end def thereAreTwoPlayers? (@p1Name && @p2Name) && !(@p2Name.text.empty? && @p2Name.text.empty?) end end
require 'pp' class Solution def self.min_cost(houses = [[]]) all_costs(houses).min end # recursively determine possible painting costs def self.all_costs(houses) return [0] if houses.empty? return houses.first.compact if houses.size == 1 costs = [] houses[0].each_with_index do |cost, paint_number| next unless cost # cost could be nil in a subsequent call from the below lines next_house = houses[1].dup next_house[paint_number] = nil all_costs([next_house] + houses[2..-1]).each do |other_cost| costs.push(cost + other_cost) end end puts "Costs" pp costs costs end end
module Dabooks class CLI::GraphCommand DETAILS = { description: 'ASCII graphing for account balances over time.', usage: 'dabooks graph <account> <filename>', schema: {}, } def initialize(clargs) @argv = clargs.free_args end def run target_account = Account[@argv.shift] balance = Amount.new(0) points = [] @argv.each do |file| transaction_set = File.open(file, 'r') { |f| Dabooks::Parser.parse(f) } transaction_set.each do |trans| trans.normalized_entries.each do |entry| if target_account.include?(entry.account) balance += entry.amount points << [trans.date, balance] end end end end points.sort_by!(&:first) if points.any? graph(points) else $stderr.puts("No transactions found") end end def graph(points) x_min, x_max = points.map(&:first).minmax y_min, y_max = points.map(&:last).minmax gutter_width = [y_min, y_max].map{ |x| Formatter.format_amount(x).length }.max data_rows = 20 data_cols = 80 data = quantize(points, data_cols, x_min, x_max, y_min, y_max, data_rows) # graph rows data_rows.downto(1) do |row| gutter = begin case when row == data_rows then Formatter.format_amount(y_max) when row == 1 then Formatter.format_amount(y_min) else '' end end print gutter.rjust(gutter_width, ' ') print "\u2551" data.each { |value| print (value >= row ? "\u2588" : ' ') } print "\u2551\n" end # x axis labels print ' '*gutter_width + "\u2560" + "\u2550"*data_cols + "\u2563\n" left_date = x_min.to_s right_date = x_max.to_s print ' '*gutter_width + "\u2551" + left_date + right_date.rjust(data_cols - left_date.length, ' ') + "\u2551\n" end def quantize(points, x_buckets, x_min, x_max, y_min, y_max, y_scale) x_buckets.times.map do |idx| lower = x_lerp(idx.to_f / x_buckets, x_min, x_max) upper = x_lerp((idx+1).to_f / x_buckets, x_min, x_max) value = bucket_value(points, lower, upper) scale_amount(value, y_min, y_max, y_scale) end end def x_lerp(factor, min, max) return min if factor <= 0 return max if factor >= 1 min_s = min.to_time.to_i max_s = max.to_time.to_i secs = factor * (max_s - min_s) time = Time.at(min_s + secs) Date.new(time.year, time.month, time.day) end def scale_amount(value, min, max, y_scale) factor = (value - min).cents.to_f / (max - min).cents.to_f factor * y_scale end def bucket_value(points, lower_bound, upper_bound) lower_value = points.reverse_each.find{ |(date, _)| date <= lower_bound }.last upper_value = points.find{ |(date, _)| date >= upper_bound }.last lower_value + Amount[((upper_value - lower_value).cents / 2.0).floor] end end end
class TeamsController < ApplicationController require 'will_paginate/array' def show @team = Team.find(params[:id]) end # GET /teams # GET /teams.json def index @teams = Team.all end def games @year = params[:year] @team = Team.find(params[:id]) @games = @team.games.where("games.year = ?", @year).order("date") render partial: "games" end def search @positions = Player.all_positions #@teams = Team.all @stats = (PlayerStats.column_names - ["id", "created_at", "updated_at"]).map{|c| [c.titleize, c]} @team_stat_names = (TeamStats.column_names - ["id", "created_at", "updated_at"]).map{|c| [c.titleize, c]} end def results teams = Team.arel_table @teams = Team.years_stats @teams = @teams.where(teams[:name].matches("%#{params[:search]}%")) if params[:search].present? @teams = @teams.where("team_years.year = ?", params[:year]) if params[:year].present? @teams = @teams.where("team_stats.wins >= ?", params[:stats]) if params[:stats].present? @teams = @teams.uniq @teams = @teams.paginate(page: params[:page]).order("name"); @title = "Results" render :index end def mostyardage teams = Team.arel_table @teams = Team.years_stats @teams = @teams.where("team_years.year = ?", params[:year]) if params[:year].present? @teams = @teams.uniq @teams = @teams.paginate(page: params[:page]).order(params[:stat_name]) @teams = @teams.reverse @title = "Query 1 results" render :index end def teamavgforpos @teams = Team.find_by_sql(["select t.* from players p, players_games pg, games g, teams t, player_stats ps where g.year = ? and (g.away_team_id = t.id or g.home_team_id = t.id) and pg.game_id = g.id and pg.team_id = t.id and p.position = ? and p.id = pg.player_id and pg.player_stats_id = ps.id group by t.id having avg(ps.?) > ?", params[:year], params[:position], params[:stats], params[:yards].to_i]) @teams = @teams.paginate(page: params[:page]) @title = "Results" render :index end def teamhaspmin @teams = Team.find_by_sql(["select t.* from players_years py, player_stats ps, players_teams pt, teams t WHERE t.id = pt.team_id AND pt.player_id = py.player_id AND py.player_stats_id = ps.id AND pt.start <= ? AND pt.end >= ? AND ps.? >= ?", params[:year], params[:year], params[:stats], params[:yards]]) @teams = @teams.paginate(page: params[:page]).uniq @title = "Results" render :index 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) Product.delete_all Product.create!(title: 'A Court of Wings and Ruin', description: %{ Feyre has returned to the Spring Court, determined to gather information on Tamlin's manoeuvrings and the invading king threatening to bring Prythian to its knees. But to do so she must play a deadly game of deceit – and one slip may spell doom not only for Feyre, but for her world as well. As war bears down upon them all, Feyre must decide who to trust amongst the dazzling and lethal High Lords – and hunt for allies in unexpected places. In this thrilling third book in the #1 New York Times bestselling series from Sarah J. Maas, the earth will be painted red as mighty armies grapple for power over the one thing that could destroy them all }, image_url: 'court.jpg', price: 7.99 )
helpers do def grandma_helper(input) if rand(100000) == 1 "I'm not grandma, I'm you! Follow me back to the pa-futur-ast!" elsif input.upcase == input "I LOVE AOL ONLINE. I MADE MY PROFILE IN #{rand(1930..1940)}" else "WHAT!?!?" end end end
module SessionsHelper def sign_in(user) session[:user_id] = user.id @current_user = user end def current_user @current_user ||= sign_in_from_session || sign_in_from_cookies unless defined?(@current_user) @current_user end def current_user?(user) user==current_user end def sign_in_from_session if session[:user_id].present? begin User.find session[:user_id] rescue session[:user_id] = nil end end end def sign_in_from_cookies if cookies[:remember_token].present? if user = User.find_by_remember_token(cookies[:remember_token]) session[:user_id] = user.id user else forget_me nil end end end def forget_me cookies.delete(:remember_token) end def signed_in? !!current_user end def sign_out session.delete(:user_id) @current_user = nil forget_me end def remember_me cookies[:remember_token] = { :value => current_user.remember_token, :expires => 2.weeks.from_now } end def signed_in_user unless signed_in? flash[:danger] = "请先登录!" redirect_to user_sign_in_path end end end
module Yoti # Encapsulates attribute anchor class Anchor attr_reader :value, :sub_type, :signed_time_stamp, :origin_server_certs def initialize(value, sub_type, signed_time_stamp, origin_server_certs) @value = value @sub_type = sub_type @signed_time_stamp = signed_time_stamp @origin_server_certs = origin_server_certs end end end
class Good < ApplicationRecord has_one_attached :thumbnail has_one :seller, class_name: 'Review', foreign_key: 'id' has_one :buyer, class_name: 'Review', foreign_key: 'id' belongs_to :user has_many :opinions has_many :added_goods, through: :opinions, source: :user enum property_type: [0, 1, 2, 3, 4] end
class Parser attr_accessor :log, :lines def initialize(log) @log = log @lines = [] @cnt = 0 end def run lines = @log.split("\n") lines.each do |line| @lines[@cnt += 1] = self.parse_line(line) end end def parse_line(line) pattern = /\d+:\d+:\d+.\d+\s{2,}\w+ – \w+.\w+\s{1,}\d+\s{2,}\d+:\d+.\d+\s{2,}\d+,\d+/ match = pattern.match(line) code = match.to_s.split(" ") return code end end
require 'spec_helper' module RailsSettings class Dummy end describe Configuration, 'successful' do it "should define single key" do Configuration.new(Dummy, :dashboard) expect(Dummy.default_settings).to eq({ :dashboard => {} }) expect(Dummy.setting_object_class_name).to eq('RailsSettings::SettingObject') end it "should define multiple keys" do Configuration.new(Dummy, :dashboard, :calendar) expect(Dummy.default_settings).to eq({ :dashboard => {}, :calendar => {} }) expect(Dummy.setting_object_class_name).to eq('RailsSettings::SettingObject') end it "should define single key with class_name" do Configuration.new(Dummy, :dashboard, :class_name => 'MyClass') expect(Dummy.default_settings).to eq({ :dashboard => {} }) expect(Dummy.setting_object_class_name).to eq('MyClass') end it "should define multiple keys with class_name" do Configuration.new(Dummy, :dashboard, :calendar, :class_name => 'MyClass') expect(Dummy.default_settings).to eq({ :dashboard => {}, :calendar => {} }) expect(Dummy.setting_object_class_name).to eq('MyClass') end it "should define using block" do Configuration.new(Dummy) do |c| c.key :dashboard c.key :calendar end expect(Dummy.default_settings).to eq({ :dashboard => {}, :calendar => {} }) expect(Dummy.setting_object_class_name).to eq('RailsSettings::SettingObject') end it "should define using block with defaults" do Configuration.new(Dummy) do |c| c.key :dashboard, :defaults => { :theme => 'red' } c.key :calendar, :defaults => { :scope => 'all' } end expect(Dummy.default_settings).to eq({ :dashboard => { 'theme' => 'red' }, :calendar => { 'scope' => 'all'} }) expect(Dummy.setting_object_class_name).to eq('RailsSettings::SettingObject') end it "should define using block and class_name" do Configuration.new(Dummy, :class_name => 'MyClass') do |c| c.key :dashboard c.key :calendar end expect(Dummy.default_settings).to eq({ :dashboard => {}, :calendar => {} }) expect(Dummy.setting_object_class_name).to eq('MyClass') end context 'persistent' do it "should keep settings between multiple configurations initialization" do Configuration.new(Dummy, :persistent => true) do |c| c.key :dashboard, :defaults => { :theme => 'red' } end Configuration.new(Dummy, :calendar, :persistent => true) expect(Dummy.default_settings).to eq({ :dashboard => { 'theme' => 'red' }, :calendar => {} }) end end end describe Configuration, 'failure' do it "should fail without args" do expect { Configuration.new }.to raise_error(ArgumentError) end it "should fail without keys" do expect { Configuration.new(Dummy) }.to raise_error(ArgumentError) end it "should fail without keys in block" do expect { Configuration.new(Dummy) do |c| end }.to raise_error(ArgumentError) end it "should fail with keys not being symbols" do expect { Configuration.new(Dummy, 42, "string") }.to raise_error(ArgumentError) end it "should fail with keys not being symbols" do expect { Configuration.new(Dummy) do |c| c.key 42, "string" end }.to raise_error(ArgumentError) end it "should fail with unknown option" do expect { Configuration.new(Dummy) do |c| c.key :dashboard, :foo => {} end }.to raise_error(ArgumentError) end end end
$LOAD_PATH.unshift File.dirname(__FILE__) $LOAD_PATH.unshift File.join(File.dirname(__FILE__), 'libs') require 'fileutils' require 'parseconfig' require 'page_control' require 'report_case/base/report_case_base' require 'report_summary' # # Function : download_xml_csv_main.rb # Parameter : # Purpose : Handle get current value of download Graph CSV and Excel-XML # Result : Pass and Fail of compare result # Comment : # Download Setting:工具→網際網路選項→安全性→自訂等級->下載→自動提示下載檔案→啟用 # def main report_summary = ReportSummary.new(basename='report_csv_xml_result') report_summary.report_one_result(['CaseName', 'DownloadXML', 'DownloadCSV']) setting = ParseConfig.new('setting.ini') website_ip = setting.params['basic']['websit_ip'] username = setting.params['basic']['username'] password = setting.params['basic']['password'] report_root_name = setting.params['page']['report_root_name'] include_rule = setting.params['page']['include_rule'].split(';') exclude_rule = setting.params['page']['exclude_rule'].split(';') pageControl = PageControl.new(report_root_name, website_ip, username, password) pageControl.set_filter_rules(exclude_rule=exclude_rule, include_rule=include_rule) expect_download_dir = File.join(report_summary.report_directory, 'Expect_Download_CSV_XML') FileUtils.mkdir_p(report_summary.current_download_dir) if !File.exist?(report_summary.current_download_dir) start_time = Time.now() while pageControl.goto_next_report_page report_case = create_report_case(pageControl.current_page_name) while report_case.goto_next_case() case_name = report_case.get_case_name() begin report_case.download_xml(report_summary.current_download_dir) result_xml = report_case.compare_xml(report_summary.current_download_dir, expect_download_dir) result_xml = result_xml ? 'Pass' : 'Failed' rescue Watir::Exception::UnknownObjectException result_xml = '-' rescue Watir::Wait::TimeoutError, RuntimeError => error result_xml = 'Failed' puts "#{case_name} #{error}" end begin report_case.download_csv(report_summary.current_download_dir) result_csv = report_case.compare_csv(report_summary.current_download_dir, expect_download_dir) result_csv = result_csv ? 'Pass' : 'Failed' rescue Watir::Exception::UnknownObjectException result_csv = '-' rescue Watir::Wait::TimeoutError, RuntimeError => error result_csv = 'Failed' puts "#{case_name} #{error}" end report_summary.report_one_result([case_name, result_xml, result_csv]) end puts "\t\t\tCurrent Total Time #{Time.now() - start_time}" puts "" end report_summary.export_report(format_type='csv_xml') puts "\t\t\tCurrent Total Time #{Time.now() - start_time}" puts "" pageControl.close report_summary.close end if __FILE__ == $0 main() end
class PagesController < ApplicationController $user_logged_in = false @user = $user_logged_in $inventory_array = [{id: 1000, name: "T-Shirt", description: "A shirt with short sleeves.", price: 12, stock: 52, vip: false, category: "tops", image: "https://target.scene7.com/is/image/Target/53294273?wid=225&hei=225&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1001, name: "Button Down", description: "A shirt with long sleeves and buttons.", price: 32, stock: 4, vip: true, category: "tops", image: "https://target.scene7.com/is/image/Target/53154813?wid=225&hei=225&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1002, name: "Tank Top", description: "A shirt with no sleeves.", price: 11, stock: 10, vip: false, category: "tops", image: "https://target.scene7.com/is/image/Target/52512718?wid=225&hei=225&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1003, name: "Straight-Leg Jeans", description: "Jeans that have straight legs.", price: 41, stock: 9, vip: false, category: "bottoms", image: "https://target.scene7.com/is/image/Target/50630840?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1005, name: "Joggers", description: "Pants that I don't think you're actually supposed to jog in.", price: 32, stock: 0, vip: true, category: "bottoms", image: "https://target.scene7.com/is/image/Target/51657225?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1008, name: "Fancy Shorts", description: "Shorts that are fancy.", price: 19, stock: 6, vip: true, category: "bottoms", image: "https://target.scene7.com/is/image/Target/50763672?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1009, name: "Sneakers", description: "Sometimes known as 'tennis shoes'", price: 62, stock: 7, vip: true, category: "shoes", image: "https://target.scene7.com/is/image/Target/52809861?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1010, name: "Sandals", description: "Shoes to wear in the sand.", price: 15, stock: 0, vip: false, category: "shoes", image: "https://target.scene7.com/is/image/Target/52903154?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1011, name: "Flats", description: "Shoes without a high heel.", price: 24, stock: 80, vip: false, category: "shoes", image: "https://target.scene7.com/is/image/Target/52822593?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "women"}, {id: 1012, name: "Button Down", description: "A shirt with buttons.", price: 36, stock: 5, vip: false, category: "tops", image: "https://target.scene7.com/is/image/Target/52449894?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1013, name: "Polo", description: "A shirt that probably has a small animal embroidered on the left chest.", price: 22, stock: 4, vip: true, category: "tops", image: "https://target.scene7.com/is/image/Target/52515130?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1014, name: "T-Shirt", description: "A shirt with short sleeves.", price: 15, stock: 0, vip: false, category: "tops", image: "https://target.scene7.com/is/image/Target/52698932?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1015, name: "Cargo Pants", description: "Pants with pockets for all of your cargo.", price: 40, stock: 8, vip: false, category: "bottoms", image: "https://target.scene7.com/is/image/Target/52515864?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1016, name: "Chinos", description: "Not jeans.", price: 33, stock: 9, vip: false, category: "bottoms", image: "https://target.scene7.com/is/image/Target/52510916?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1017, name: "Jeans", description: "Denim pants", price: 48, stock: 7, vip: true, category: "bottoms", image: "https://target.scene7.com/is/image/Target/AA_RTW_OctWk3_catnav_mens_jeans_athleticstraight101827-170928_1506629391648?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1018, name: "Boots", description: "These are made for walking.", price: 96, stock: 17, vip: true, category: "shoes", image: "https://target.scene7.com/is/image/Target/52846955?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1019, name: "Sneakers", description: "Shoes for sneaking.", price: 79, stock: 34, vip: false, category: "shoes", image: "https://target.scene7.com/is/image/Target/52687116?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"}, {id: 1020, name: "Oxfords", description: "Fancy shoes.", price: 91, stock: 4, vip: false, category: "shoes", image: "https://target.scene7.com/is/image/Target/52474761?wid=328&hei=328&qlt=80&fmt=pjpeg", men_or_women: "men"} ] def home @title = "We Dress Impecably 56" end def log_in @user end def sign_up @user end def customer_profile @user end def women @inventory = $inventory_array end def men @inventory = $inventory_array end def vip @user @inventory = $inventory_array end def edit_profile @user end def contact @store_hours = [ {day: "Monday", open: "10:00am - ", close: "9:00pm"}, {day: "Tuesday", open: "10:00am - ", close: "9:00pm"}, {day: "Wednesday", open: "10:00am - ", close: "9:00pm"}, {day: "Thursday", open: "10:00am - ", close: "9:00pm"}, {day: "Friday", open: "10:00am - ", close: "9:00pm"}, {day: "Saturday", open: "11:00am - ", close: "9:00pm"}, {day: "Sunday", open: "11:00am - ", close: "6:00pm"} ] end end
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 module TwitterCldr module Tokenizers class PatternTokenizer attr_reader :data_reader, :tokenizer def initialize(data_reader, tokenizer) @data_reader = data_reader @tokenizer = tokenizer end def tokenize(pattern) tokenizer.tokenize(expand(pattern)) end private def expand(pattern) if pattern.is_a?(Symbol) # symbols mean another path was given path = pattern.to_s.split(".").map(&:to_sym) data = data_reader.pattern_at_path(path) next_pattern = data.is_a?(Hash) ? data[:pattern] : data expand_pattern(next_pattern) elsif pattern.is_a?(Hash) pattern.inject({}) do |ret, (key, val)| ret[key] = expand(val) ret end else pattern end end end end end
module CloudFoundry def self.raw_vcap_data ENV['VCAP_APPLICATION'] end def self.vcap_data if is_environment? JSON.parse(raw_vcap_data) else nil end end # returns `true` if this app is running in Cloud Foundry def self.is_environment? !!raw_vcap_data end def self.instance_index if is_environment? vcap_data['instance_index'] else nil end end end
if Rails.env.production? || Rails.env.staging? raise "MAILCHIMP_LIST_ID is missing" if ENV["MAILCHIMP_LIST_ID"].nil? raise "MAILCHIMP_API_KEY is missing" if ENV["MAILCHIMP_API_KEY"].nil? end
class CreateLcResults < ActiveRecord::Migration[5.2] def change create_table :lc_results do |t| t.integer :lc_class_id t.string :name t.integer :runner_id t.string :ecard t.string :club t.string :start t.string :result t.string :rank t.string :speed t.string :loss_rate t.string :total_relative t.string :total_losstime t.string :ideal_time t.timestamps end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.require_version ">= 1.3.5" VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "precise32" config.vm.box_url = "http://files.vagrantup.com/precise32.box" # Use vagrant-cachier or similar if available (https://github.com/fgrehm/vagrant-cachier) config.cache.auto_detect = true # Shell provisioning script config.vm.provision :shell, :path => "vagrantBootstrap/bootstrap.sh" config.vm.network :private_network, ip: "192.168.10.5" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. # config.vm.synced_folder "../data", "/vagrant_data" # Share folder over NFS (option ignored automatically by Vagrant for Windows) config.vm.synced_folder ".", "/vagrant", :nfs => true end
require "spec_helper" describe BigML::Source do describe "#code" do it "return code when set" do source = BigML::Source.new('code' => 201) source.code.should == 201 end it "return nil when not set" do source = BigML::Source.new('code' => nil) source.code.should be_nil end it "extract source id from resource" do source = BigML::Source.new('resource' => 'souce/4f66a0b903ce8940c5000000') source.id.should == "4f66a0b903ce8940c5000000" end end end
# -*- encoding : utf-8 -*- module EverythingClosedPeriodsHelper def samfundet_closed? EverythingClosedPeriod.current_period end end
module Shomen module Model # class Method < Abstract # def initialize(settings={}) super(settings) @table['declarations'] ||= [] end # Method's name. attr_accessor :name # Method's namespace. attr_accessor :namespace # Comment accompanying method definition. attr_accessor :comment # Format of comment (rdoc, markdown or plain). attr_accessor :format # Singleton method `true` or `false/nil`. attr_accessor :singleton # Delarations is a list of keywords that designates characteristics # about a method. Common characteristics include `reader`, `writer` # or `accessor` if the method is defined via an attr method; `public` # `private` or `protected` given the methods visibility; and `class` # or `instance` given the methods scope. Default designations are # are impled if not specifically stated, such as `public` and `instance`. # # Using a declarations list simplifies the Shomen data format by allowing # declarations to be freely defined, rather than creating a field for each # possible designation possible. attr_accessor :declarations # Aliases. attr_accessor :aliases # Aliases. attr_accessor :alias_for # Breakdown of interfaces signature, arguments, parameters, block argument # an return values. attr_accessor :interfaces # def interfaces=(array) self['interfaces'] = ( array.map do |settings| case settings when Interface settings else Interface.new(settings) end end ) end # List of possible returns types. attr_accessor :returns # List of possible raised errors. attr_accessor :raises # Method generated dynamically? attr_accessor :dynamic # Filename. attr_accessor :file # Line number. attr_accessor :line # Source code. attr_accessor :source # Source code language. attr_accessor :language # Deprecated method. alias :parent :namespace # def to_h h = super h['!'] = 'method' h['interfaces'] = (interfaces || []).map{ |s| s.to_h } h end end end end
class Api::V1::GoalsController < Api::V1::BaseController def index goals = Goal.where(goal_params) render :json => goals.as_json end def create goal = Goal.new(goal_params) if goal.save render :json => goal.as_json else render :json => goal.errors.as_json end end def update goal = Goal.find(params[:id]) if goal.update(goal_params) render :json => goal.as_json else render :json => goal.errors.as_json end end def destroy goal = Goal.find(params[:id]) if goal.destroy render :json => {:success => true} else render :json => {:success => false} end end private def goal_params params.permit(:id, :name, :exercise_type, :goal_number, :current_value, :user_id) end end
# ASSUMPTIONS # # Not using any Gem, but a direct HTTP request to access YouTube provided API. # The value of the KEYWORD string to search through YouTube is given static as 'football' require "net/https" require "uri" require 'json' class YouTube attr_accessor :keyword KEYWORD = "football" def initialize(keyword) @keyword = keyword end # To frame the request body. def frame_request(keyword=nil) # Parsing the YouTube query URL. uri = URI.parse("https://gdata.youtube.com/feeds/api/videos?q=#{keyword}&max-results=3&alt=json&orderby=relevance&v=2") # Creating a new http object using Net::HTTP with ssl enabled. http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Creating HTTP request using the formatted URI. request = Net::HTTP::Get.new(uri.request_uri) return http, request end # To hit YouTube and parse the response def search http, request = frame_request @keyword # Getting response from YouTube response = http.request(request) # Parsing for serialization of the response json_response = JSON.parse(response.body) # Any mishaps inside the code-block will return an empty array. begin json_response['feed']['entry'].map{ |rsp| rsp['media$group']['media$content'].first.send(:[],'url') } rescue [] end end end # Example to check with the keyword provided as a constant inside YouTube class you_tube = YouTube.new YouTube::KEYWORD # Displaying the result (maximum of 3 urls as an array). puts you_tube.search.inspect require 'test/unit' class YouTubeTest < Test::Unit::TestCase def setup @you_tube = YouTube.new YouTube::KEYWORD @keyword = @you_tube.keyword end # To test the Keyword. def test_keyword assert_equal @you_tube.keyword, YouTube::KEYWORD end # To test the custom Keyword. def test_custom_keyword @you_tube = YouTube.new "benchprep" assert_equal @you_tube.keyword, "benchprep" end # Test for maximum size of the result array. def test_search assert @you_tube.search.length <= 3 end # Test for empty result array. def test_for_empty_result assert_not_equal @you_tube.search.length, 0 end end
class AddQuestionsToPins < ActiveRecord::Migration def change add_column :pins, :questions, :text end end
class Packaging < Tag validates :name, presence: true, uniqueness: true has_many :product_packagings has_many :products, through: :product_packagings end
require 'sshkit/runners/abstract' module SSHKit module Runner class Abstract private def backend(host, &block) back = SSHKit.config.backend.new(host, &block) back.instance_variable_set(:@user, @options[:root_user]) if @options[:root_user] back end end end end
require 'rails_helper' RSpec.describe User, type: :model do subject { described_class.new(first_name: "Peter", last_name: "Nolan", email: "example@example.com", password: "password", password_confirmation: "password") } describe 'Validations' do it 'is valid with valid attributes' do expect(subject).to be_valid expect(subject.errors.full_messages.length).to eql(0) end it 'is not valid without a password' do subject.password = nil expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("Password can't be blank") end it 'is not valid without a password_confirmation' do subject.password_confirmation = nil expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("Password confirmation can't be blank") end it 'is not valid when password and password_confirmation do not match' do subject.password_confirmation = "somethingelse" expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("Password confirmation doesn't match Password") end it 'is not valid without email' do subject.email = nil expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("Email can't be blank") end it 'is not valid without unique email' do User.create(first_name: "John", last_name: "Doe", email: "john@doe", password: "password", password_confirmation: "password") subject.email = "JOHN@DOE" expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("Email has already been taken") end it 'is not valid with a password less than 8 characters' do subject.password = "pass" subject.password_confirmation = "pass" expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("Password is too short (minimum is 8 characters)") end it 'is not valid without a first_name' do subject.first_name = nil expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("First name can't be blank") end it 'is not valid without a last_name' do subject.last_name = nil expect(subject).to_not be_valid expect(subject.errors.full_messages[0]).to eql("Last name can't be blank") end end describe '.authenticate_with_credentials' do it 'returns user object if credentials are valid' do subject.save! expect(User.authenticate_with_credentials("example@example.com", "password")).to_not eql(nil) end it 'returns nil if email is invalid' do subject.save! expect(User.authenticate_with_credentials("incorrect@email", "password")).to eql(nil) end it 'returns nil if password is invalid' do subject.save! expect(User.authenticate_with_credentials("example@example.com", "notcorrect")).to eql(nil) end it 'returns user object if valid email contains spaces before or after' do subject.save! expect(User.authenticate_with_credentials(" example@example.com ", "password")).to_not eql(nil) end it 'returns user object if valid email contains unmatching case characters' do subject.save! expect(User.authenticate_with_credentials("eXaMpLe@ExAmPlE.cOm", "password")).to_not eql(nil) end end end
require_relative "abstract" class SpotifyClient < AbstractClient def initialize(auth) @api = Spotify::Client.new( access_token: auth.token, raise_errors: true, persistent: true, ) super end # :nocov: # def me @api.me end def ensure_playlist(playlist) spotify_playlist = @api.user_playlists(@auth.external_id)["items"].find do |x| x["id"] == playlist.spotify_id || x["name"] == playlist.spotify_title end if spotify_playlist spotify_playlist["track_uris"] = @api.user_playlist_tracks( @auth.external_id, spotify_playlist["id"] )["items"].map { |x| x["track"]["uri"] } else spotify_playlist = @api.create_user_playlist( @auth.external_id, playlist.spotify_title, false ) spotify_playlist["track_uris"] = [] end spotify_playlist end def ensure_track(spotify_playlist, track) track.queries.each do |query| search_tracks = @api.search(:track, query)["tracks"]["items"] # puts query.inspect # puts search_tracks.map { |x| "#{x["artists"].map{ |a| a["name"] }.join(",")} – #{x["name"]}" }.inspect # puts "-"*10 if search_track = search_tracks.first if spotify_playlist["track_uris"].find { |x| x == search_track["uri"] } break end Retriable.retriable do @api.add_user_tracks_to_playlist( @auth.external_id, spotify_playlist["id"], [search_track["uri"]] ) end spotify_playlist["track_uris"] << search_track["uri"] spotify_playlist["track_uris"].uniq! break end end end def cleanup @api.close_connection end private # TODO def invalidate_token end # :nocov: # end
FactoryGirl.define do factory :plan do name { Faker::Book.title } planner { Faker::Name.first_name } location { Faker::Address.city } end end
require "pry" # Helper Method def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [ [0,1,2], # top row win [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def won?(board) ### ways to check if won?(board) is a falsey value ### # won?(board) == nil, !won?(board) WIN_COMBINATIONS.detect do |win_combo| #check a tic tac toe board and return true if there is a win and false if not. #return the winning combination indexes as an array if there is a win. w1 = win_combo[0] w2 = win_combo[1] w3 = win_combo[2] # win_combo [0,1,2] # all tokens in a line have to be the same # condition = board[w1] == board[w2] && board[w1] == board[w3] && board[w1] != " " end #end detect #return false end #end def def full?(board) board.all? {| slot | slot == "X" || slot == "O"} end def draw?(board) !won?(board) && full?(board) end def over?(board) draw?(board) || full?(board) || won?(board) end def winner(board) #board.all? {| slot | slot == "X" && slot == "X" && slot == "X"} # if won?(board) # index = won?(board)[0] # board[index] # end win_combo = won?(board) if win_combo index = win_combo[0] board[index] end # win_combo = won?(board) # board[win_combo[0]] if win_combo end
describe Parser::BostonRetirementSystem do include_context "parser" let(:file) { file_fixture("sample_boston_retirement_system.csv") } it "parses a row" do expect(record[:sort_name]).to eql("KIRK, JAMES T") expect(record[:job_description]).to eql("Teacher - S20315") end end
class AddHtmlSummaryToJobdesc < ActiveRecord::Migration def self.up rename_column :jobdescs, :text, :txt add_column :jobdescs, :html, :text add_column :jobdescs, :summary, :text end def self.down remove_column :jobdescs, :html remove_column :jobdescs, :summary end end
require 'rails_helper' describe StaticPagesHelper do it 'resource name' do expect(resource_name).to eq(:user) end it 'resource' do resource expect(@resource).to be_a_new(User) end it 'devise_mapping' do devise_mapping expect(@devise_mapping).to be_instance_of(Devise::Mapping) end end
require 'rails_helper' RSpec.describe 'Stats', type: :request do describe 'GET /stats/weekly' do before do create(:trip, distance: 15.5, price: BigDecimal('15.15')) create(:trip, distance: 12.75, price: BigDecimal('10.50')) get '/api/stats/weekly' end let(:expected_result) do { total_distance: '28km', total_price: '25.65PLN' } end it 'returns http success' do expect(response).to have_http_status(:success) end it 'returns proper stats' do expect(response.body).to eq(expected_result.to_json) end end describe 'GET /stats/monthly' do let(:second_day_of_month) { DateTime.now.at_beginning_of_month + 2.days } let(:expected_result) do [ { day: "#{second_day_of_month.strftime('%B')}, 2nd", total_distance: '16km', avg_ride: '16km', avg_price: '15.15PLN' }, { day: "#{seventh_day_of_month.strftime('%B')}, 7th", total_distance: '38km', avg_ride: '19km', avg_price: '15.00PLN' } ] end let(:seventh_day_of_month) { DateTime.now.at_beginning_of_month + 7.days } before do create(:trip, distance: 15.50, price: BigDecimal('15.15'), date: second_day_of_month) create(:trip, distance: 24.20, price: BigDecimal('17.50'), date: seventh_day_of_month) create(:trip, distance: 14.00, price: BigDecimal('12.50'), date: seventh_day_of_month) get '/api/stats/monthly' end it 'returns http success' do expect(response).to have_http_status(:success) end it 'returns proper stats' do expect(response.body).to eq(expected_result.to_json) end end end
require "rails_helper" RSpec.describe Post do it 'has a valid factory' do factory = FactoryGirl.create(:post) expect(factory).to be_valid end it 'is valid with valid attributes' do post = FactoryGirl.build(:post) expect(post).to be_valid end it 'is not valid without a title' do post = FactoryGirl.build(:post, title: nil) expect(post).to_not be_valid end it 'is not valid with a name shorter than 5 characters' do post = FactoryGirl.build(:post, title: 'abc') expect(post).to_not be_valid end end
=begin - Add two methods: ::generic_greeting(class) and #personal_greeting(instance) =end class Cat attr_reader :name def initialize(name) @name = name end def self.generic_greeting puts "Hello! I'm a cat!" end def personal_greeting puts "Hello! My name is #{name}!" end end kitty = Cat.new('Sophie') Cat.generic_greeting # Hello! I'm a cat! kitty.personal_greeting # Hello! My name is Sophie!
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib")) require 'bosdk/enterprise_session' module BOSDK describe EnterpriseSession do before(:each) do @session_mgr = mock("ISessionMgr").as_null_object @session = mock("IEnterpriseSession").as_null_object @infostore = mock("IInfoStore").as_null_object @infoobjects = mock("IInfoObjects").as_null_object class CrystalEnterprise; end CrystalEnterprise.should_receive(:getSessionMgr).at_least(1).with.and_return(@session_mgr) @session_mgr.should_receive(:logon).at_least(1).with('Administrator', '', 'cms', 'secEnterprise').and_return(@session) @session.should_receive(:getService).at_least(1).with('', 'InfoStore').and_return(@infostore) @es = EnterpriseSession.new('cms', 'Administrator', '') end describe "#new" do it "should accept an optional locale setting" do EnterpriseSession.new('cms', 'Administrator', '', :locale => 'en_CA') end end describe "#connected?" do before(:each) do @session.should_receive(:logoff).at_most(1).with.and_return end it "returns 'true' when connected to a CMS" do @es.connected?.should be_true end it "returns 'false' when not connected to a CMS" do @es.disconnect @es.connected?.should be_false end end describe "#disconnect" do before(:each) do @session.should_receive(:logoff).once.with.and_return end it "should disconnect from the CMS" do @es.disconnect @es.connected?.should be_false end it "shouldn't raise an error when not connected" do lambda{2.times{ @es.disconnect }}.should_not raise_exception end end describe "#path_to_sql" do before(:each) do @path_query = 'path://SystemObjects/Users/Administrator@SI_ID' @stmt = "SELECT SI_ID FROM CI_SYSTEMOBJECTS WHERE SI_KIND='User' AND SI_NAME='Administrator'" @stateless_page_info = mock("IStatelessPageInfo").as_null_object class PagingQueryOptions; end PagingQueryOptions.should_receive(:new).once.with @infostore.should_receive(:getStatelessPageInfo).once.with(@path_query, nil).and_return(@stateless_page_info) @stateless_page_info.should_receive(:getPageSQL).once.with.and_return(@stmt) end it "should convert a path query to an sql query" do @es.path_to_sql(@path_query).should == @stmt end end describe "#query" do context "when :type => sql" do before(:each) do @stmt = 'SELECT * FROM CI_INFOOBJECTS' @infostore.should_receive(:query).once.with(@stmt).and_return([]) end it "should send the statement to the underlying InfoStore" do @es.query(@stmt) end end context "when :type => path://" do before(:each) do @path_query = 'path://SystemObjects/Users/Administrator@SI_ID' @stmt = "SELECT * FROM CI_SYSTEMOBJECTS WHERE SI_KIND='User' AND SI_NAME='Administator'" @es.should_receive(:path_to_sql).once.with(@path_query).and_return(@stmt) @infostore.should_receive(:query).once.with(@stmt).and_return([]) end it "should convert a path:// query to sql before execution" do @es.query(@path_query) end end context "when :type => query://" do before(:each) do @path_query = 'query://{SELECT * FROM CI_INFOOBJECTS}' @stmt = 'SELECT * FROM CI_INFOOBJECTS' @es.should_receive(:path_to_sql).once.with(@path_query).and_return(@stmt) @infostore.should_receive(:query).once.with(@stmt).and_return([]) end it "should convert a query:// query to sql before execution" do @es.query(@path_query) end end context "when :type => cuid://" do before(:each) do @path_query = 'cuid://ABC' @stmt = "SELECT * FROM CI_INFOOBJECTS WHERE SI_CUID='ABC'" @es.should_receive(:path_to_sql).once.with(@path_query).and_return(@stmt) @infostore.should_receive(:query).once.with(@stmt).and_return([]) end it "should convert a cuid:// query to sql before execution" do @es.query(@path_query) end end end describe "#open_webi" do before(:each) do @webi_report_engine = mock("WebiReportEngine").as_null_object @document_instance = mock("DocumentInstance").as_null_object @webi_instance = mock("WebiInstance").as_null_object class WebiReportEngine; end class WebiInstance; end WebiInstance.should_receive(:new).at_least(1).with(@document_instance).and_return(@webi_instance) @webi_report_engine.should_receive(:open).at_least(1).with("1234").and_return(@document_instance) end context "when :locale => en_US" do before(:each) do WebiReportEngine.should_receive(:new).once.with(@session, 'en_US').and_return(@webi_report_engine) end it "should create a WebiReportEngine and call #open" do @es.open_webi("1234") end it "should only create a WebiReportEngine once" do 2.times{@es.open_webi("1234")} end it "should create a WebiInstance and return it" do @es.open_webi("1234").should == @webi_instance end end context "when :locale => en_CA" do before(:each) do WebiReportEngine.should_receive(:new).once.with(@session, 'en_CA').and_return(@webi_report_engine) end it "should pass any specified locale" do es = EnterpriseSession.new('cms', 'Administrator', '', :locale => 'en_CA') es.open_webi("1234") end end end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate private def authenticate authentication_text = 'Administration password required. Please enter username && password.' authenticate_or_request_with_http_basic(authentication_text) do |username, password| md5_of_password = Digest::MD5.hexdigest(password) login = Variable.find_by_key 'login' password = Variable.find_by_key 'password' username == (login ? login.value : 'victor') && md5_of_password == (password ? password.value : "c31f554d04b62050782143c540ab1941") end end end
require 'test_helper' class ExtensionTest < Test::Unit::TestCase context String do should "return the string for to_param" do string = "my string!" assert_same string, string.to_param end end context Integer do should "return a string representation for to_param" do integer = 5 assert_equal "5", integer.to_param end end end
# Build a class EmailParser that accepts a string of unformatted # emails. The parse method on the class should separate them into # unique email addresses. The delimiters to support are commas (',') # or whitespace (' '). class EmailParser attr_reader :emails def initialize(email_string) @emails = email_string end def parse @emails.scan(/(\w+@\w+.\w+)/).flatten.uniq end end