text stringlengths 10 2.61M |
|---|
require 'rails_helper'
describe Review, type: :model do
subject { build :review }
context 'associations' do
it { should belong_to(:book) }
it { should belong_to(:user) }
end
context 'aasm state change' do
it 'pending -> approved' do
expect(subject).to transition_from(:pending).to(:approved)... |
require 'rails_helper'
RSpec.describe "collections/index", :type => :view do
before(:each) do
assign(:collections, [
FactoryGirl.create(:collection),
FactoryGirl.create(:collection)
])
end
it "renders" do
render
end
end
|
class Location < ActiveRecord::Base
has_many :ingredients
before_destroy :remove_child_associations
validates_presence_of :name
has_ancestry
private
def remove_child_associations
ingredients.each do |ingredient|
ingredients.delete(ingredient)
end
end
end
|
class KakeBowling
include Enumerable
def self.game pins
result = 0
10.times do |frame|
frame_position = frame*2
result += score(pins, frame_position) + score(pins, frame_position+1)
if got_strike(pins, frame_position)
result += (pins[frame_position+2] + pins[frame_position+2+1])
... |
module Antlr4::Runtime
class UnsupportedOperationException < StandardError
end
class IllegalStateException < StandardError
end
class ATNDeserializer
SERIALIZED_VERSION = 3
class << self
attr_accessor :SERIALIZED_Uuid
attr_accessor :SERIALIZED_VERSION
@@base_serialized_uuid = UUID... |
module Jekyll
class Expert
include Convertible
attr_accessor :data, :content
attr_accessor :expert_data
def initialize(site, base, dir, name)
@site = site
@expert_data = self.read_yaml(File.join(base, dir), name)
@expert_data["content"] = markdownify(self.content)
end
de... |
require "bunny"
class Rabbit
attr_accessor :conn, :channel, :q
def initialize
@conn = Bunny.new
conn.start
@channel = conn.create_channel
@q = channel.queue("hello-rabbit", durable: true)
end
def post(message)
channel.default_exchange.publish(message, routing_key: q.name)
puts "[x] S... |
class IncomePolicy < ApplicationPolicy
def index?
user.role.can_view_income
end
def create?
user.role.can_create_income
end
def update?
user.role.can_update_income
end
def destroy?
user.role.can_destroy_income
end
end |
require 'rails_helper'
RSpec.describe Company, type: :model do
subject { FactoryGirl.build :company}
describe 'validations' do
it { is_expected.to be_valid }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_uniqueness_of(:name) }
end
describe 'methods' do
it { ex... |
class SessionsController < ApplicationController
def new
end
def create
user = User.auth(params[:session][:email], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combo."
render 'new'
else
session[:user_id] = user.id
redirect_to awards_url... |
class Follower < ActiveRecord::Base
attr_accessible :user_id, :followable_id, :followable_type
belongs_to :followable, :polymorphic => true
belongs_to :user
after_create :notify_user, :increment_follower_count
def notify_user
if self.followable_type == 'User'
NotificationService.new('user_follower... |
class FontLabrada < Formula
head "https://github.com/google/fonts.git", branch: "main", only_path: "ofl/labrada"
desc "Labrada"
homepage "https://github.com/Omnibus-Type/Labrada"
def install
(share/"fonts").install "Labrada-Italic[wght].ttf"
(share/"fonts").install "Labrada[wght].ttf"
end
test do
... |
# encoding: utf-8
require "rubygems"
require 'sequel'
# Load migrations
Sequel.extension :migration, :core_extensions
# Load inflector (String.classify)
Sequel.extension :inflector
require 'chronic'
require 'money'
require 'yaml'
require 'erb'
require 'trollop'
require 'pathname'
# require serenity 0.2.2
require File... |
module Grape
module OAuth2
module Helpers
# Grape Helper object for OAuth2 requests params.
# Used fin default Grape::OAuth2 gem endpoints and can be used
# for custom one.
module OAuthParams
extend ::Grape::API::Helpers
# Params are optional in order to process them corre... |
class CreateRaceTimes < ActiveRecord::Migration
def change
create_table :race_times do |t|
t.integer :race_id
t.integer :lane
t.integer :lane_id
t.float :elapsed_seconds
t.timestamps
end
add_index :race_times, :race_id
add_index :race_times, :lane
end
end
|
class UserCompSchedulesController < ApplicationController
def create
@user_comp_schedule = UserCompSchedule.new(user_comp_schedule_params)
if @user_comp_schedule.save
redirect_to competition_infos_path, notice: t('flash.cmp_shcedule.create')
else
render 'competition_infos/index'
end
end
... |
require 'adapter_environment'
require 'diffa/token_generator'
class UsersController < ApplicationController
# POST /users
# POST /users.json
def create
token = request.query_parameters['authToken']
if not token.nil? and token == AdapterEnvironment::AUTH_TOKEN
user_token = Diffa::TokenGenerator.ge... |
# Bitmap Export v5.4 for XP, VX and VXace by Zeus81
# Free for commercial use
# Licence : http://creativecommons.org/licenses/by/4.0/
# Contact : zeusex81@gmail.com
# How to Use :
# - exporting bitmap :
# bitmap.export(filename)
# or bitmap.save(filename)
#
# - serialize bitmap :
# open(filename, 'w... |
class AgreementtemplatesController < ApplicationController
before_action :authenticate_user!
def index
@templates=Agreementtemplate.all_templates(current_user.company_id)
end
def get_agreement_titles
@templates=Agreementtemplate.all_templates(current_user.company_id)
render json:@templates.map{|x|... |
# frozen_string_literal: true
class Staff::Api::V1::OrganizationsController < ApplicationController
before_action :authenticate_staff!
before_action :set_organization, only: %i[destroy]
def index
@organizations = Organization.order(created_at: :desc)
render json: OrganizationSerializer.new(@organization... |
class RenameInstallsPurchaseDateToPurchasedAt < ActiveRecord::Migration
def self.up
remove_index :installs, :purchase_date
rename_column :installs, :purchase_date, :purchased_at
add_index :installs, :purchased_at
end
def self.down
remove_index :installs, :purchased_at
rename_column :inst... |
class EnrollmentsController < ApplicationController
authorize_resource
before_filter :ensure_user_input
def ensure_user_input
redirect_to edit_user_path(current_user) unless current_user.valid?
end
# GET /enrollments
# GET /enrollments.xml
def index
@enrollments = Enrollment.all
respond_to... |
class Video
include Mongoid::Document
include Mongoid::Timestamps
field :description, type: String
field :size, type: Integer, default: 0
field :length, type: Integer, default: 0
field :url, type: String
validates :description, presence: true
validates :size, numericality: {only_integer: true}
valid... |
class DynamicRecord::FieldDescription < DynamicRecord::Base
self.table_name = :dynamic_record_field_descriptions
serialize :valid_choices, Array
#should i normalize some of these empty fields into
#a has_many metadata thing?
attr_accessible :field_name, :field_kind, :validator,
:valid_choices, :prio... |
class UsersController < ApplicationController
before_filter :authenticate!
respond_to :json
def show
@user = current_user
respond_to do |format|
format.html
format.json { render json: @user, serializer: UserSerializer }
end
end
end
|
require 'uri'
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :current_user
protected
helper_method :current_user, :signed_in?, :user_check, :good_redirect
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
def current_user=(us... |
require_relative "piece.rb"
require "colorize"
require "byebug"
require_relative "cursor"
class Board
attr_accessor :board
CHESS_PIECES = {
Rook => [[0,0], [0,7], [7,0], [7,7]],
Knight => [[0,1], [0,6], [7,1], [7,6]],
Bishop => [[0,2], [0,5], [7,2], [7,5]],
Queen => [[0,3], [7,3]],
King =>... |
class HourlyEmployee < Employee
attr_reader :name,:email
def initialize(name,email,hourly_rate, hours_worked)
super(name,email)
@hourly_rate = hourly_rate
@hours_worked = hours_worked
end
def calculate_salary
@hourly_rate * @hours_worked
end
end
|
class AddCategoryIdToFund < ActiveRecord::Migration
def change
add_column :funds, :category_id, :integer
add_index :funds, :category_id
end
end
|
class A217489Builder
def self.sequence(terms = 100)
seq = [2]
numbers = (3..5_000).select { |n| !(n.to_s =~ /1/) }
while seq.length < terms
next_term = numbers.find { |n| condition(n, seq.last) }
numbers -= [next_term]
seq << next_term
end
seq
end
def self.condition(n, m)
... |
class OrdersController < ApplicationController
before_action :require_user_admin
def index
@orders = Order.all
end
def new
@order = Order.new
@order.build_customer
end
def create
@order = Order.new(params_order)
if @order.save
flash[:warning] = "Correct Create- "
render '... |
require 'rails_helper'
RSpec.describe Timeline, type: :model do
describe 'Require validations' do
it 'should has a content' do
should validate_presence_of(:content)
end
end
describe 'Has Associations' do
it 'has many reacts' do
should have_many(:reacts)
end
it 'has many comments... |
class ProductBlock < ApplicationRecord
belongs_to :product
validates :blocked_stock, presence: true, on: :create
end
|
class FontNotoSansBengali < Formula
head "https://noto-website-2.storage.googleapis.com/pkgs/NotoSansBengali-unhinted.zip", verified: "noto-website-2.storage.googleapis.com/"
desc "Noto Sans Bengali"
homepage "https://www.google.com/get/noto/#sans-beng"
def install
(share/"fonts").install "NotoSansBengali-B... |
Pod::Spec.new do |s|
s.name = "PRKTableViewController"
s.version = "1.0"
s.summary = "基于Three20框架提取优化的TableView框架 "
s.homepage = "https://github.com/passerbycrk/PRKTableViewController"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Passerbycrk" => "passerby... |
require 'rails_helper'
describe Phone do
it "does not allow duplicate phone numbers per contact" do
contact = Contact.create(
firstname: 'Joe',
lastname: 'Tester',
email: 'joetester@example.com'
)
contact.phones.create(
phone_type: 'home',
phone: '785-555-1234'
)
mob... |
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "john.doe#{n}@example.org" }
password "secret1234"
end
trait :confirmed do
confirmed_at { Time.now }
end
end
|
json.array!(@pick_ups) do |pickup|
json.set! :id, pickup.id
json.set! :title, pickup.partner.name
json.set! :description, pickup.comment
json.set! :className, pickup.complete? ? 'fc-dist-complete' : 'fc-dist-scheduled'
json.start pickup.issued_at
json.end pickup.issued_at
json.url pickup_day_distributions... |
module TestHelpers::ModelTestHelper
def self.included(base)
base.extend(ClassMethods)
base.send(:include, InstanceMethods)
end
module ClassMethods
def help_testing(klass, default_args = nil)
default_args ||= {}
method_ending = klass.name.demodulize.underscore
create_... |
class Role < ApplicationRecord
belongs_to :user
belongs_to :subject, polymorphic: true
enum role: {
membership_secretary: 1
}
def self.membership_secretary_emails
Role.membership_secretary.collect(&:user).collect(&:email)
end
end
# == Schema Information
#
# Table name: roles
#
# id :in... |
module Omega
class Sprite < Omega::Drawable
attr_accessor :position, :scale, :origin, :flip
attr_accessor :angle, :mode, :color
attr_accessor :width, :height
attr_accessor :visible
attr_accessor :movable
attr_reader :options, :image
# Options
# - ... |
shared_examples_for 'Allows a testimonial to be edited' do
before do
raise "please set let(:initial_path)" if initial_path.blank?
ensure_on(initial_path)
end
describe 'when saving and returning to index' do
it 'updates testimonial', :js => true do
expect(page).to have_content('Update me')
... |
class NuntiumController < ApplicationController
before_filter :authenticate
def receive_at
render :json => Subscriber.modify_subscription_according_to(params)
end
private
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == Nuntium::Config['incoming_u... |
require 'test_helper'
class LikeTest < ActiveSupport::TestCase
def setup
@like = likes(:Like1)
end
test "like created and associated with author and content_item" do
assert_equal(@like.liked.title, "Title1", "Like not set to content_item")
assert_equal(@like.liker.email, "dave... |
class CreateTableSongCeremonies < ActiveRecord::Migration
def change
create_table :song_ceremonies do |t|
t.integer :song_id, :ceremony_id
t.string :song_type
t.timestamps
end
end
end
|
FactoryBot.define do
factory :user do
email { 'teste@treinadev.com.br' }
login { 'treinadev' }
password { '12345678' }
end
end
|
# frozen_string_literal: true
class Series < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
has_many :connection_series, class_name: 'Resource::Connection::Series', dependent: :destroy
has_many :resources, through: :connection_series
validates :name, presence: true, uniqueness: true
... |
module MonthlyReports
module Collection
module Categories
class Stats
class Methods
private
attr_reader :categories_stats_presenter
public
def initialize(categories_stats_presenter)
@categories_stats_presenter = categories_stats_presenter
... |
require "rails_helper"
RSpec.describe Api::V1::ItemsController, type: :controller do
describe "GET #index.json" do
let(:json_response) { JSON.parse(response.body) }
it "responds with successful 200 HTTP status code" do
get :index, format: :json
expect(response).to be_success
expect(respon... |
#!/usr/local/ruby/bin/ruby
#description_start
# 自动将log/production.log文件备份到以当天日期为名称的文件
# 比如:2008-10-16-1.production.log
# 最后面的1为版本号,default为1,如果一天轮换多次,版本号递增
# 2008-10-16-2.production.log,2008-10-16-3.production.log以此类推
#description_end
require "fileutils"
require "date"
# 得到某天的版本号
def get_version(source_dir,log_file_n... |
class CreateCommentsTable < ActiveRecord::Migration[5.0]
def change
create_table :comments do |table|
table.string :content
table.integer :user_id
table.integer :image_id
end
end
end
|
class AddStatusToUsers < ActiveRecord::Migration[6.0]
def change
add_column :api_v1_users, :status, :string
end
end
|
class CreateTables < ActiveRecord::Migration
def change
# 基础
# --------
create_table "users", :force => true do |t|
t.string "name", :default => "", :null => false
t.string "hashed_password", :default => "", :null => false
t.string "salt", ... |
class PagesController < ApplicationController
def index
@result = []
end
def search
@is_mobile = is_mobile?
if !params[:search].nil?
@result = Emoji.tagged_with(split_into_array(search_params[:tag_list]))
@search = search_params[:tag_list]
else
@result = []
end
render "index"
end
private
... |
# Card object
class Card
attr_accessor :suit, :value, :face
def initialize(suit, value)
@suit = suit
@value = value
@face = 'up'
end
def card_info
self.suit + " " + self.value
end
end
|
class AddSizeToInventoryItem < ActiveRecord::Migration
def change
add_column :inventory_items, :size, :string
end
end
|
$imported ||= {}
$kms_imported ||= {}
module Bubs
module GGPatch
# * Gauge File Names
# Images must be placed in the "Graphics/System" folder of your project
ALCHSYNTH_EXP_IMAGE = "GaugeHP"
# * Gauge Position Offset [x, y]
ALCHSYNTH_EXP_OFFSET = [-23, -2]
# * Gauge Length Adjustment
A... |
# coding: utf-8
class ApplicationController < ActionController::Base
before_action :set_current_user
add_flash_types :success, :info, :warning, :danger
def set_current_user
@current_user = User.find_by(id: session[:user_id])
end
def forbid_not_logged_in
if @current_user == nil
flash[:danger] ... |
module Ransack
module Helpers
module FormHelper
private
def order_indicator_for(order)
if order == 'asc'
'<i class="fa fa-sort-asc"></i>'
elsif order == 'desc'
'<i class="fa fa-sort-desc"></i>'
else
'<i class="fa fa-sort"></i>'
end
... |
class ShippingAddress < ApplicationRecord
belongs_to :end_user
validates :zip_code, length: { is: 7 }
validates :address, presence: true
validates :order_name, presence: true
def zip_code_and_address_and_order_name
self.zip_code + self.address + self.order_name
end
end
|
class Admin::BaseAdminController < ApplicationController
before_action :ensure_active_employee!
before_action :authenticate
before_action :set_app_settings
before_action :init_new_notification
before_action :set_notifications_and_messages
before_action :set_attendance
before_action :set_wfh_requests
bef... |
class ExperimentRunner
class << self
def check_result(result)
@expected ||= result
raise "Wrong result? #{result} (expected #{@expected})" if result != @expected
end
def run(experiment)
print_title(experiment)
run_measuring_time(experiment)
run_profiling_memory(experiment)
... |
class ChangeFavoriteCountInRestaurant < ActiveRecord::Migration[5.1]
def change
change_column(:restaurants, :favorites_count, :integer, :default => 0, :null=> false)
end
end
|
class PicturesController < ApplicationController
def index
list
render :action => 'list'
end
# GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
verify :method => :post, :only => [ :destroy, :create, :update ],
:redirect_to => { :action => :list }
def list
@picture_pages... |
# # require File.join(File.dirname(__FILE__), 'gilded_rose')
require "./lib/gilded_rose.rb"
#
describe GildedRose do
describe "#update_quality" do
#
it "updates quality of each item" do
item1 = double("Item")
item2 = double("Item")
item3 = double("Item")
expect(item1).to receive_messages(... |
class SessionsController < ApplicationController
def new
end
def create
@user = User.find_by_lowercase_username(params[:username].downcase) || User.find_by_email(params[:username])
respond_to do |format|
if @user.present? && @user.authenticate(params[:password])
# if @user.verified?
... |
class User < ApplicationRecord
has_secure_password
validates :password, confirmation: true
validates :email, :password, :password_confirmation, :name, presence: true
end
|
class AddPrescriberContactInfo < ActiveRecord::Migration
def change
add_column :meds, :email, :string
end
end
|
class Puppy
def initialize
puts "initializing new puppy instance..."
end
def fetch(toy)
puts "I brought back the #{toy}!"
end
def speak(int)
puts "Howl" * int
end
def rollover
puts "Rollover"
end
def dog_years (x)
puts x*7
end
def fetch_news
puts "Here's the paper"... |
require File.expand_path '../../spec_helper.rb', __FILE__
describe 'User endpoints' do
context '/user' do
let(:endpoint) { '/user' }
it_behaves_like 'an endpoint with appropriate OPTIONS response'
context 'GET' do
let!(:user) { create(:user) }
subject { get endpoint }
it 'retrieves al... |
require_relative 'tic_tac_toe_node'
class SuperComputerPlayer < ComputerPlayer
def move(game, mark)
t_t_t = TicTacToeNode.new(game.board, mark)
children = t_t_t.children.shuffle
children.any? { |child| return child.prev_move_pos if child.winning_node?(mark) }
children.any? { |child| return child.pre... |
class Scale < ActiveRecord::Base
has_many :visits_reports
validates_presence_of :name
end
|
class Result
attr_accessor :name
attr_accessor :value
attr_accessor :units
attr_accessor :flags
attr_accessor :timestamp
attr_accessor :reference_ranges
attr_accessor :dilution
## here will call mappings and check the result correlation
def initialize(line)
line.fields[2].scan(/\^{4}(?<name>[A-Za-z0-9\%\#]+... |
# Encapsulates methods used on the Dashboard that need some business logic
module DateRangeHelper
def date_range_params
params.dig(:filters, :date_range).presence || this_year
end
def date_range_label
case (params.dig(:filters, :date_range_label).presence || "this year").downcase
when "yesterday"
... |
# frozen_string_literal: true
require 'test_helper'
module Vedeu
module Logging
describe ClockTime do
describe '.clock_time' do
subject { Vedeu.clock_time }
context 'when Process::CLOCK_MONOTONIC is defined' do
it { subject.must_be_instance_of(Float) }
end
# ... |
require "html_enumerator"
module PricingCalculator
class LetterCounter
def initialize(page:, letter:)
@page = page
@letter = letter
end
def call
nodes.inject(0) do |sum, element|
if element.text?
sum += element.text.count(letter)
else
sum
end... |
class Screenshot < ActiveRecord::Base
belongs_to :project
mount_uploader :image, ScreenshotUploader
validates :image, presence: true
end
|
# encoding: utf-8
require 'hallon'
require 'bundler/setup'
require 'base64'
require 'sinatra'
require 'addressable/uri'
require 'json'
require 'gon-sinatra'
require 'sinatra/reloader' if development?
Sinatra::register Gon::Sinatra
unless "".respond_to?(:try)
class Object
alias_method :try, :send
end
class... |
Given('Enter given url and click on signin link') do
@dockerPage = DockerPage.new
@dockerPage.loginAsUser
end
When('Enter incorrect username and incorrect password') do
@dockerPage.navigateToPages
end
Then('Verify error messages') do
@dockerPage.signOnWeb
end
When('Enter correct username and correct password... |
# Problem 334: Spilling the beans
# http://projecteuler.net/problem=334
# In Plato's heaven, there exist an infinite number of bowls in a straight line.
# Each bowl either contains some or none of a finite number of beans.
# A child plays a game, which allows only one kind of move: removing two beans from any bowl, an... |
require 'rails_helper'
describe 'Crawler' do
before(:each) do
@crawler = Crawler.new('http://www.makersacademy.com', 1)
end
describe '#return_hash' do
it 'returns a hash with url, title and links_array keys' do
expect(@crawler.return_hash.keys).to include(:url, :title, :links_array)
end
... |
# == Schema Information
#
# Table name: post_links
#
# id :bigint(8) not null, primary key
# slug :string(255)
# post_id :bigint(8)
#
class PostLink < ApplicationRecord
belongs_to :post, class_name: 'Post'
validates :slug, uniqueness: true
end
|
class FaqsController < ApplicationController
before_action :admin_user, only: [:destroy, :create]
def index
@categories = Category.all.where(is_active: true).order('created_at ASC')
@cat = Category.all.where("categories.category_id IS NOT NULL")
@apply = ApplyNow.all
category = Category.friend... |
require "erb"
require "fpm/namespace"
require "fpm/package"
require "fpm/errors"
# TODO(sissel): Add dependency checking support.
# IIRC this has to be done as a 'checkinstall' step.
class FPM::Target::Solaris < FPM::Package
def architecture
case @architecture
when nil, "native"
@architecture = %x{unam... |
class AddIngredientIdToChangees < ActiveRecord::Migration
def change
add_column :changes, :ingredient_id, :integer
add_index :changes, :ingredient_id
end
end
|
require './input_processor.rb'
require 'spec_helper'
RSpec.describe InputProcessor do
let(:filename) { 'test_input.txt' }
let(:processor) { InputProcessor.new(filename) }
context 'sample_input' do
let(:filename) { 'sample_input.txt' }
it '#initialize' do
expect(processor.pattern_strings).to eq(["... |
module CheapDependency
def self.cd_test?
'test' == ENV[CHEAP_DEPENDENCY_ENV_NAME]
end
def self.cd_test(load)
ENV[CHEAP_DEPENDENCY_ENV_NAME] = 'test' if load
ENV[CHEAP_DEPENDENCY_ENV_NAME] = 'no_test' unless load
end
def self.cd_exists_absolute_fn(relative_fn_base)
afn = File.expand_path("#{... |
# encoding: UTF-8
class Order < ActiveRecord::Base
has_many :line_items, dependent: :destroy
validates :email, :phone, presence: true
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
scope :in_progress, ->{where("orders.checked_out_at IS... |
# needed for documentation
class CashRegister
def initialize
@total = 0.00
@change = 0.00
end
def total
@total
end
def purchase(amount)
@total += amount
end
def pay(paid)
if paid > total
@change = paid -= total
@total = 0
else
@total -= paid
end
end
de... |
class User < ApplicationRecord
devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:validatable,
:confirmable
has_many :posts, dependent: :nullify
has_many :comments, dependent: :nullify
end
|
q = Palette.find_by_name("fees_due")
if q.present?
q.palette_queries.destroy_all
end
q.instance_eval do
user_roles [:admin,:finance_control,:fee_submission,:finance_reports,:revert_transaction] do
with do
all(:conditions=>["((ffc.id IS NOT NULL AND (fa_fc.id IS NULL OR fa_fc.is_deleted = false)) OR
... |
class ApplicationController < ActionController::Base
helper_method :current_user_session, :current_user
before_filter :force_utf8_params
before_filter :set_charset
protect_from_forgery
def force_utf8_params
traverse = lambda do |object, block|
if object.kind_of?(Hash)
object.each_value { |o| traver... |
# frozen_string_literal: true
class FeedsController < ApplicationController
def index
@feeds = Feed.from_subscriptions_with_unread_articles(
current_user.subscriptions,
articles_per_feed: 3,
page: current_page,
feeds_per_page: 5
)
respond_to do |format|
format.html
for... |
require_relative 'astar'
class Cave
attr_reader :goblins, :elves
def initialize(cavearr, elf_attack_power = 3)
@elves = []
@goblins = []
@cave = cavearr.each_with_index.map do |row,y|
row.each_with_index.map do |caveitem,x|
case caveitem
when '#'
Wall.new(x,y)
... |
#! ruby -Ku
=begin
2015/08/01
日記を書くためスクリプト
jsonの読み込み
=end
require "fileutils"
require "kconv"
require "json"
############################################################
#変数とか
nikki_data = {} #日記自体。空のハッシュ
############################################################
#メインの処理
file = open("nikki_output/nikki_data... |
require 'rspec/expectations'
require 'appium_lib'
require 'rspec/retry'
RSpec.configure do |config|
GH_RELEASE = 'https://github.com/saucelabs/my-demo-app-rn/releases/download/v1.2.0'.freeze
config.exceptions_to_retry = [Selenium::WebDriver::Error::UnknownError, Selenium::WebDriver::Error::ServerError]
config.d... |
# the variable 'days' is set to a string containing days of the week
days = "Mon Tue Wed Thu Fri Sat Sun"
# the variable 'months' is set equal to various months. New lines are added in.
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
puts "Here are the days: #{days}"
puts "Here are the months: #{months}"
# formattin... |
require "spec_helper"
describe PriorityTest::Core::TestResult do
subject { PriorityTest::Core::TestResult.new }
[ :status, :started_at, :run_time ].each do |field|
it "validates presence of #{field}" do
expect {
subject.save
}.to raise_error {
Sequel::ValidationFailed
}
... |
class CreatePlacementRegistrations < ActiveRecord::Migration
def self.up
create_table :placement_registrations do |t|
t.references :student
t.references :placementevent
t.boolean :is_applied ,:default=>false
t.boolean :is_approved
t.boolean :is_attended,:default=>false
t.boolea... |
class Maths::Number
attr_reader :number
def initialize(number)
@number = number
end
def factorial
if (self.number < 0)
Float::INFINITY
elsif (self.number == 0)
1
else
# HACK: Should be simplified
number = self.number
self.number = self.number - 1
number * se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.