text
stringlengths
10
2.61M
require 'fileutils' require 'date' require 'digest/md5' class Reversion attr_reader :tracked_files, :manifest, :last_commit def initialize(repo_dir) @repo_dir = repo_dir @manifest = File.join @repo_dir, 'manifest' if File.directory?(@repo_dir) # If repo already exists, load it load = loa...
# frozen_string_literal: true module Decidim module Opinions # A command with all the business logic when a user destroys a draft opinion. class DestroyOpinion < Rectify::Command # Public: Initializes the command. # # opinion - The opinion to destroy. # current_user - The current ...
class ServicesController < ServiceBaseController skip_before_action :set_service, only: [:new, :create] def show end def new @service = @company.services.build render layout: 'application' end def create @service = @company.services.build(service_params) if @service.save flash[:succ...
module CGL class Error < StandardError; end class InvalidCommand < Error; end class PileNotFound < Error; 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
require 'rails_helper' RSpec.describe NichesController, type: :controller do login_user let(:user) { subject.current_user } let(:niche) { create(:niche, user: user) } let(:parent_niche) { create(:new_niche, user: user) } let(:valid_attributes) { attributes_for(:niche).merge(user_id: user.id) } let(:invali...
require 'rspec' require 'ele_prog_int' describe "even_odd" do it "reorder array so even entries appear first" do result1 = even_odd([1,2,4,5,6,]) expect(result1).to eq([6,2,4,5,1]) end end describe "edit_distance" do it "return minimum of updates to match two strings" do result1 = edit_distance("sun...
class AgendaDatatable include Rails.application.routes.url_helpers delegate :params, :h, :link_to, :number_to_currency, :number_with_delimiter, to: :@view delegate :conference_id, to: :@conference_id delegate :laws_only, to: :@laws_only delegate :current_user, to: :@current_user def initialize(view, curren...
class RemovePresentationSlideColumns < ActiveRecord::Migration def change if column_exists?(:presentation_slides, :raw_html_content) remove_column :presentation_slides, :raw_html_content, :text end if column_exists?(:presentation_slides, :parsed_json_content) remove_column :presentation_slides...
require 'email_alert/mail_payload' class MailProcessor def initialize (mail_message_id) @mail_message_id = mail_message_id end delegate :subject, :body, :has_template, :mail_recipient_list, :sender, :mail_attachments, :additional_info, :to => :mail_message delegate :recipients, :recipient_type, :recipien...
class PackingListsController < ApplicationController before_action :authorize_user, only: [:new, :edit, :create, :update, :destroy] before_action :set_packing_list, only: [:show, :edit, :update, :destroy] before_action :set_deal, except: [:states, :show] def index end def new @job_request_ids = [] ...
class Api::V1::JobListingsController < ApplicationController def index if params[:company_id] company = Company.find(params[:company_id]) job_listings = company.job_listings render json: { job_listings: JobListingSerializer.new(job_listings).serializabl...
# frozen_string_literal: true module GeoPattern module Helpers def require_files_matching_pattern(pattern) Dir.glob(pattern).sort.each { |f| require_relative f } end # Makes an underscored, lowercase form from the expression in the string. # # @see ActiveSupport # It's MIT-Licensed ...
#-- # Copyright (c) 2010-2012 Michael Berkovich, tr8nhub.com # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, mod...
require 'active_support/core_ext/module/delegation' module Paperclip class AbstractAdapter OS_RESTRICTED_CHARACTERS = %r{[/:]} attr_reader :content_type, :original_filename, :size delegate :binmode, :binmode?, :close, :close!, :closed?, :eof?, :path, :readbyte, :rewind, :unlink, :to => :@tempfile al...
require "application_system_test_case" class FacilityUsesTest < ApplicationSystemTestCase setup do @facility_use = facility_uses(:one) end test "visiting the index" do visit facility_uses_url assert_selector "h1", text: "Facility Uses" end test "creating a Facility use" do visit facility_us...
require "#{Rails.root}/lib/RakeHelper.rb" include RakeHelper desc 'setup root of tag hierarchy' task tag_web_setup: :environment do Organization.find_each do |o| abort = false tag_names = ["root","processes","services","products","materials"] tag_names.each do |tag_name| if o.find_existing_tag(tag_...
require "test_helper" feature "As a site visitor I want to comment on Blog Posts So that I can troll my friends" do scenario "comment on blog posts" do # Given a published post (in Fixtures) # When I visit the post visit post_path(posts(:published)) # I can fill out a comment form fill_in :c...
require "./lib/schedule" describe DailySchedule do subject(:daily) { DailySchedule.new(working_hours, busy_hours) } let(:working_hours) { (9..18).to_a } let(:busy_hours) { [14, 15, 18] } describe "#available?" do it "should return false if all hours are included in working hours" do expect(daily.avai...
# frozen_string_literal: true class BridgeOffice < ApplicationRecord include Excom extend Ordered EMAILS = { commander: 'cdr', executive: 'xo', administrative: 'ao', educational: 'seo', secretary: 'secretary', treasurer: 'treasurer', asst_educational: 'aseo', asst_secretary: 'asec' }.freeze bel...
class DropSwipes < ActiveRecord::Migration def up drop_table :rails_admin_histories drop_table :swipes end def down create_table "rails_admin_histories", :force => true do |t| t.text "message" t.string "username" t.integer "item" t.string "table" t.integer "mon...
=begin Compare two strings by comparing the sum of their values (ASCII character code). For comparing treat all letters as UpperCase. Null-Strings should be treated as if they are empty strings. If the string contains other characters than letters, treat the whole string as it would be empty. Examples: "AD","BC" -> eq...
# http://classic.battle.net/war3/human/units/footman.shtml class Footman < Unit def initialize super(60, 10) end def attack!(enemy) if enemy.is_a?(Barracks) power = attack_power / 2.0 enemy.damage(power.ceil) else super end end end
class AddAlreadyReviewedToEstimates < ActiveRecord::Migration def change add_column :estimates, :already_reviewed, :boolean end end
require 'rspec/core' require 'rspec/core/rake_task' desc "Run API and Core specs" RSpec::Core::RakeTask.new do |t| t.rspec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""] t.pattern = FileList['spec/**/*_spec.rb'] end desc "Run all specs in spec directory with RCov" RSpec::Core::RakeTask.new(:...
#Vlue~ #Music_Player.play(:jbells) module Music_Player SOUNDS = { :basic => 'Audio/SE/Switch1' } NOTES = { :d => [SOUNDS[:basic],80], :e => [SOUNDS[:basic],85], :f => [SOUNDS[:basic],90], :g => [SOUNDS[:basic],95], :A => [SOUNDS[:basic],100], :B => [SOUNDS[:basic],105], :C => [SOUN...
require "gemnasium/parser" require "open-uri" require "json" module Gemgrapher class Grapher def content(string) @content ||= begin indent = string.scan(/^[ \t]*(?=\S)/) n = indent ? indent.size : 0 string.gsub(/^[ \t]{#{n}}/, "") end end def initialize @content = content(File.read...
class Event < ActiveRecord::Base has_many :users, through: :event_users has_many :event_users has_many :exchanges end
require_relative "dwelling" require_relative "occupant" require_relative "Useful_Methods" require 'Date' class Apartment < Dwelling include Useful_Methods attr_reader :rent, :lease_start_date, :lease_end_date def initialize(address, city, state, zip_code, rent, lease_start_date, lease_end_date, max_capacity=3...
class UserGroup < ApplicationRecord has_many :category_groups, class_name: 'CategoryGroup', foreign_key: 'group_id' has_many :categories, through: :category_groups has_many :book_threads validates :name, uniqueness: true end
require 'open-uri' require 'openssl' class DownloadService def self.get_download_info(download) logger = Logger.new(File.join(Rails.root, 'log', 'resque.log')) download_target = Array.new download.each do |line| master = Pathname.new(Dbase.first.master) parent = master + line.parent_path ...
require 'base64' require 'uri' require 'net/http' module DecodeDataURI def DecodeDataURI::decode_data_uri(uri) uri = URI.parse(uri) unless uri.kind_of? URI raise ArgumentError.new("Incorrect URI scheme, expected data:, got #{uri.scheme}") unless uri.scheme == 'data' # extract the media type and ...
# accepts a recap of a game formatted like so: # "Team One score, Team Two score" class Game # initially I was just score[-1].to_i TEAM_SCORE_REGEX = /(.+)( \d*)/ attr_accessor :team_one, :team_two def initialize(recap) @recap_array = prepare(recap) @team_one = @recap_array[0] @team_two = @rec...
RSpec.describe 'Merchant update page' do before(:each) do @merchant_1 = Merchant.create(name: 'Beer World') end it 'should show merchant name' do visit "/merchants/#{@merchant_1.id}/edit" expect(page).to have_content("Edit: #{@merchant_1.name}") end it 'should fill in form with Merchant name' do...
class RecipeStepsController < ApplicationController before_action :set_recipe_step, only: [:show, :edit, :update, :destroy] # GET /recipe_steps # GET /recipe_steps.json def index @recipe_steps = RecipeStep.all.order(:recipe_id,:step_order) end # GET /recipe_steps/1 # GET /recipe_steps/1.json def s...
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.role == "Super Admin" can :manage, :all elsif user.role == "Admin" can :manage, :all cannot :create, User elsif user.role == "User" can :read, :a...
class Patient < ActiveRecord::Base validates :name, presence: true, length: { minimum: 5 } validates :age, presence: true validates :provider, presence: true end
source 'https://rubygems.org' gem 'rails', '~> 5.2.0' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.1.0', require: false gem 'base_indexer', '~> 4.2' gem 'discovery-indexer', '~> 3.0', '>= 3.1.2' gem 'responders', '~> 2.0' # Build JSON APIs with ease. Read more: https://git...
Rails.application.routes.draw do devise_for :users resources :bookings, except: [:new, :create] resources :au_pairs, only: [:index, :show] do resources :bookings, only: [:new, :create] resources :reviews, only: [:create] end root to: 'pages#home' end
module Resource::Storage::A3Par def self.table_name_prefix 'resource_storage_a3_par_' end end
FactoryBot.define do factory :product_category do id {Faker::Number.number} name {Faker::App.name} expense {false} end end
require "rails_helper" RSpec.describe IpLease, type: :model do subject { build(:ip_lease) } describe "Validations" do it "is valid with valid attributes" do expect(subject).to be_valid end it "is invalid with invalid attributes" do expect(build(:ip_lease, { nic: nil },)).to_...
class Bst VERSION = 1 attr_accessor :data, :left, :right def initialize(data) @data = data end def insert(val) if val <= data left ? left.insert(val) : self.left = Bst.new(val) else right ? right.insert(val) : self.right = Bst.new(val) end end def each(&block) ret...
module BadgeConcerns module EnrolledLearningTrackBadgeable extend ActiveSupport::Concern include BadgeConcerns::SimpleBadgeable included do after_update :award_on_complete_learning_track end private def award_on_complete_learning_track quantity = self.user.enrolled_learning_track...
############################################################ # # Name: Sean Glover # Assignment: Extra Credit #4 - Leap Years # Date: 01/22/2013 # Class: CIS 282 # Description: Prompt user for starting year and ending year then print only leap years # ##########################################...
class Admin < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable def self.GetDefaultAdmin @invincibleAdmin = Admin.all().order('...
module Model module History class VarRecord include Mongoid::Document include Mongoid::Timestamps embedded_in :entity, class_name: ::Model::Entity::VarEntity.to_s field :current, type: Float field :previous, type: Float end end end
class Page < ActiveRecord::Base belongs_to :lesson belongs_to :organization acts_as_list :column => :position, :scope => :lesson belongs_to :author, :class_name => "User", :foreign_key => "author_id" has_many :questions, :as => :questionable before_save :sanitize_title validates_presence_of :title ...
class Trackrole < ActiveRecord::Base attr_accessible :code, :name has_many :trackspeakers, :foreign_key => "trackrole_code", :primary_key =>"code" end
module Linguistics module Latin module Verb class LatinVerb =begin rdoc #-- # The purpose of this module is to contain the metaprogramming modules # method_missing and respond_to? in a place that's nice and neat. # ++ =end =begin rdoc === DESCRIPTION Override of the method_missing method. A lot of the ...
#Largest string possible from given numbers class Solution attr_accessor :array def initialize(a) @array = a end def do_merge_sort(first=0, last=@array.size-1) return if first >= last mid = (first + last)/2 do_merge_sort(first, mid) do_merge_sort(mid+1, last) do_s...
# reads from random.org API and posts to requestb.in API require 'net/http' require 'uri' require 'json' # prepare the random.org https request uri = URI.parse("https://api.random.org/json-rpc/1/invoke") header = {'Content-Type':'application/json'} body = {"jsonrpc":"2.0","method":"generateIntegers","params":{"apiKey...
define :base_ppa, { :url => nil } do base_ppa_params = params raise "base_ppa command is only available on ubuntu" if node['platform'] != "ubuntu" raise "Please specify url with base_ppa" unless base_ppa_params[:url] package "python-software-properties" execute "apt-get-update" do command "apt-get ...
require 'test_helper' class FinanceOutflowsControllerTest < ActionController::TestCase setup do @finance_outflow = finance_outflows(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:finance_outflows) end test "should get new" do get :new ...
module Kinata class Cinema CINEMAS = { :arena_zapad => 877, :arena_mall => 5981, :arena_mladost => 2540, :cinema_city => 3664, :euro_cinema => 6088, :mtel_imax => 3663, :vlaikova => 3, :dom_na_kinoto => 29, } attr_accessor :cinema de...
# モデルでテストすべきは以下の点です。 # メッセージを保存できる場合 # メッセージがあれば保存できる # 画像があれば保存できる # メッセージと画像があれば保存できる # メッセージを保存できない場合 # メッセージも画像も無いと保存できない # group_idが無いと保存できない # user_idが無いと保存できない # 今回の場合、テストのケースが # メッセージを保存できる場合、 # メッセージを保存できない場合 # で分かれています。 # 今回の場合、テストのケースが # メッセージを保存できる場合、 # メッセージを保存できない場合で分かれています。 # このように、特定の条件でテストをグループ分けし...
class Person attr_accessor :name include Enumerable def initialize(name) @name = name end def <=> (person) @name <=> person.name end def to_s @name end end
Rails.application.routes.draw do devise_for :users root "home#index" resources :colleges, only: [:new, :create] do get :activate, on: :collection resources :admins, only: [:index, :new, :create] end resources :staffs, only: [:index, :new, :create, :edit, :update] resources :courses, only: [:index, ...
require File.expand_path(File.dirname(__FILE__) + '/acceptance_helper') feature "Issues" do background do @issue = FactoryGirl.create(:issue) end scenario "Viewing" do article = FactoryGirl.create(:article, issue: @issue) visit issue_path @issue page.should have_content @issue.title page...
require 'minitest/autorun' require 'minitest/reporters' require 'minitest/skip_dsl' require 'csv' require_relative '../lib/order' require_relative '../lib/online_order' require_relative '../lib/customer' describe "OnlineOrder" do let(:all) {Grocery::OnlineOrder.all} let(:find_extra) {Grocery::OnlineOrder.find(150...
require 'ffi' module CityHash LOW64_MASK = 0x0000000000000000ffffffffffffffff HIGH64_MASK = 0xffffffffffffffff0000000000000000 module Internal extend FFI::Library ffi_lib( case RUBY_PLATFORM when /darwin/ File.join(File.dirname(__FILE__), '..', 'ext', 'cityhash', 'cityhash.bun...
# frozen_string_literal: true module PieceHelper # Returns the vector distance between "from" and "to" def distance_vector(from, to) [to, from].transpose.map { |x| x.reduce(:-) } end end
class CreateGroups < ActiveRecord::Migration def change create_table :groups do |t| t.string :title t.integer :year, null: false t.integer :speciality_id, null: false t.boolean :active, default: false t.timestamps null: false end end def unchange drop_table :gr...
class AddDefaultToColumns < ActiveRecord::Migration def change change_column :orders, :columns_shown, :string, :default => "all" end end
module EARMMS::ThemeHelpers def find_template(views, name, engine, &block) if views.instance_of? Hash _, folder = views.detect do |k, v| engine == Tilt[k] end folder ||= views[:default] else folder = views end begin raise "no theme dir" unless settings.theme_di...
class MainController < ApplicationController def index @deliveries = Delivery.all @delivery_ids = @deliveries.map{|d| d.id} respond_to do |format| format.html format.js end end def validate_parameters() params_validation() params_completing() render json: params.to_json end...
#!/usr/bin/env ruby require 'yaml' require 'date' require 'debugger' require 'time' require_relative 'timestream-feeder' class Monitor attr_accessor :device attr_accessor :responseType attr_accessor :transId attr_accessor :fineGrain attr_accessor :adapting attr_accessor :serialnum attr_accessor :instan...
class Application < Sinatra::Base configure do Dir[File.join(Sinatrails.root, 'lib/sinatrails', '*.rb')].each{|file| require file } env = ENV['RACK_ENV'] || 'development' Bundler.require env set :raise_errors, false enable :sessions enable :logging disable :run enable :method_overrid...
require 'rails_helper' RSpec.describe GroceryItem, type: :model do it "should have a valid factory" do expect(FactoryGirl.create(:grocery_item)).to be_valid end end
class Comment < ApplicationRecord belongs_to :user belongs_to :spot mount_uploader :comment_image,ImagesUploader validates :comment,presence: true,length: {minimum:4,maximum:90} end
class Task < ApplicationRecord belongs_to :user has_many :task_labels, dependent: :destroy has_many :labels, through: :task_labels, inverse_of: :tasks accepts_nested_attributes_for :task_labels, allow_destroy: true validates :name, presence: true, length: { maximum: 100 } validates :content, presence: true...
require 'test_helper' class InterestsControllerTest < ActionDispatch::IntegrationTest setup do @interest = interests(:one) end test "should create register interest then redirect to thank you page" do assert_difference('Interest.count') do post interests_url, params: { interest: { first_name: 'Oll...
module MailUp class Error < StandardError end class BadRequest < Error end class ClientError < Error end class NotFound < Error end class ServerError < Error end class TooManyRequests < Error end class Unauthorized < Error end class Unavailable < Error end end
class ChangeAttenderRefferenceToClassToClassDate < ActiveRecord::Migration[5.0] def change rename_column :attenders, :class_id, :class_date_id end end
class CroaksController < ApplicationController before_action :confirm_logged_in, only: [:create, :destroy] before_action :confirm_matching, only: :destroy #action to create a new croak from the home page def create @croak = current_user.croaks.build(croak_params) if @croak.save flash[:success] = "...
require 'rake/packagetask' BUILD_DIR = "releases" QUIET = {verbose: false} task :source => BUILD_DIR directory BUILD_DIR version = `git rev-parse --short HEAD 2>/dev/null | tr -d "\n"` Rake::PackageTask.new(:fiat, version) do |p| p.need_tar_gz = true p.package_dir = BUILD_DIR task :source => p.package_dir_pa...
class Account < ApplicationRecord belongs_to :user has_many :balances PLATFORMS = %i[no_platform bitso yo_te_presto briq afluenta la_tasa cetes_directo red_girasol] enum platform: PLATFORMS lockbox_encrypts :settings, type: :json scope :updateable, -> { where.not(platform: :no_platform) } scope :foreig...
class Power < ActiveRecord::Base validates :name, :rating, :description, presence: true validates :rating, numericality: {less_than_or_equal_to: 10} has_many :abilities has_many :heros, through: :abilities end
namespace :twitter do ############################### # Streaming # ############################### desc 'stream tweets' task :stream => :environment do require 'rubygems' require 'tweetstream' puts "#####################################" puts "# Starting streaming twitter feed #" p...
class Market::Category < ActiveRecord::Base has_many :subcategories, inverse_of: :category, dependent: :destroy, class_name: '::Market::Category' belongs_to :category, inverse_of: :subcategories, class_name: '::Market::Category' validates :name, presence: true scope :ordered, -> { order(:position) } scope ...
class CreateBusinessCardBatches < ActiveRecord::Migration def self.up create_table :business_card_batches do |t| t.integer :quantity t.boolean :printed t.string :batch_name t.timestamps end end def self.down drop_table :business_card_batches end end
# encoding: UTF-8 module CDI module V1 module LearningTracks class LearningDynamicLinkService < BaseLinkResourceService action_name :link_learning_dynamic def user_can_associated_resource? unless valid_learning_dynamic? return not_found_error!('learning_dynamics.not_...
class ApplicationController < ActionController::Base after_action :track_action, unless: :ignored_ip_address? def track_action VisitEvent.create(controller_name: controller_name, action_name: action_name) end def ignored_ip_address? request.remote_ip == ENV['IGNORED_IP'] end end
require "fileutils" require "pathname" require "log4r" require "support/isolated_environment" module Unit class IsolatedEnvironment < ::IsolatedEnvironment def create_vagrant_env(options=nil) options = { :cwd => @workdir, :home_path => @homedir }.merge(options || {}) Vagrant:...
# frozen_string_literal: true require "beyond_api/utils" module BeyondApi class Token class InvalidSessionError < StandardError; end include BeyondApi::Utils attr_reader :session def initialize(session) @session = session raise InvalidSessionError, "Invalid session" unless session.is...
# frozen_string_literal: true require_relative '../postgresql.rb' module Postgresql class Sample < ActiveRecord::Base establish_connection( adapter: Postgresql::ADAPTER, host: '0.0.0.0', username: 'sample', password: 'password', database: 'sample' ) scope :with_title, -> {...
class Intructor::LessonsController < ApplicationController def new @section = section.find(params[:section_id]) end end
require_relative 'day21' describe 'swap position' do let(:word) { 'abcde' } let(:expected) { 'acbde' } it 'works' do actual = swap_position word, 1, 2 expect(actual).to eq expected end it 'works in reverse' do actual = swap_position expected, 1, 2 expect(actual).to eq word end end descri...
class AddColmunToItems < ActiveRecord::Migration[5.0] def change add_column :items, :brand_id, :integer add_column :items, :item_condition_id, :integer, null: false add_column :items, :postage_payer_id, :integer, null: false add_column :items, :size_id, :integer, null: false add_column :items, :pr...
require 'rails_helper' RSpec.describe UsersController, :type => :controller do describe "GET check" do before { create(:user) } it "gets a good auth" do get :check, { auth_token: "validAuth", format: :json } expect(response).to have_http_status(:success) expect(response.body).to eq({}.to_...
require 'spec_helper' describe Review do context "validating the rating system" do it 'should not have a rating more than 5'do review = Review.new(comments: 'it was Awesome!', rating:10) expect(review).to have(1).error_on(:rating) end it 'should not have a rating less than 1' do re...
# # Cookbook Name:: owncloud # Recipe:: default # # Copyright 2014, oshiire # # All rights reserved - Do Not Redistribute # execute "adding-gpg-oc" do command "curl -L http://download.opensuse.org/repositories/isv:ownCloud:community/Debian_7.0/Release.key | apt-key add -" not_if "apt-key list | egrep -q 'ownCloud'"...
class ApplicationWorker include Sidekiq::Worker include Sidekiq::ProgressBar DEFAULT_QUEUE = Rails.application.class.to_s.split('::').first.underscore.dup.freeze DEFAULT_RETRY = false sidekiq_options queue: (( defined? QUEUE ) ? QUEUE : DEFAULT_QUEUE ), retry: !!(( defined? RETRY ) ? RETRY : DEFAULT_RETRY ...
require File.expand_path(File.dirname(__FILE__) + '/../test_config.rb') describe "Account Model" do before do @account = Account.create({ email: "admin@admin.co.uk", password: "testpassword", }) end it 'can construct a new instance' do account = Account.new refute_nil account end ...
Soulmate::Helpers.module_eval do #accepts hebrew def normalize(str) str.downcase.gsub(/[^a-z0-9\u0590-\u05FF ]/i, '').strip end end Soulmate::Loader.class_eval do # "id", "term", "score", "aliases", "data" def add(item, opts = {}) opts = { :skip_duplicate_check => false }.merge(opts) ...
class FileNameAnalyzer < WordSearch::Analysis::Analyzer def append_suffixes(array, text, offset) sc = StringScanner.new(text) until sc.eos? array << sc.pos + offset sc.skip(%r{[^/.]*[/.]?}) end array end end
# Write a method that displays a 4-pointed diamond in an n x n grid, where n # is an odd integer that is supplied as an argument to the method. You may # assume that the argument will always be an odd integer. Example: # diamond(3) == # * # *** # * def make_row(count, width) diamonds = '*' * (count * 2 + 1) pu...
module Behaviour module Aggressor def weaponry(target = nil) weaps = {} alters = [] weapons = [] self.each_applicable_effect do |effect| weapons << effect if effect.respond_to?(:weapon_intent) alters << effect if effect.respond_to?(:alter_attack_intent) end # Generate weapons weapons....
# Author:: Prabhu Das (<prabhu.das@clogeny.com>) # Copyright:: Copyright (c) 2013 Opscode, Inc. require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'chef/knife/cloud/fog/service' =begin require 'support/shared_examples_for_fog_service' describe Chef::Knife::Cloud::FogService do it_behaves_...
class PostsController < ApplicationController before_action :authorize_post_view, only: :edit def index end def show @post = Post.find(params[:id]) @user = User.find(@post.user_id) #find the user of the current post. end def new # @user = User.find params[:id] # @post = @use...