text stringlengths 10 2.61M |
|---|
# 基本メソッド
str = 'timtim is cool guy'
str.empty? # => false
"".empty? # => true
str.length # => 18
str.size # => 18
str.include?("guy") # => true
str.start_with?("tim") # => true
# 演算
'tim' + 'tim' # => "timtim"
'tim' * 3 # => "timtimtim"
"Result: %04d" % 42 # => "Result: 0042"
str = "Tim"
str << "tim"
str # => "Timtim... |
class CreateDailyEtls < ActiveRecord::Migration
def change
create_table :daily_etls do |t|
t.decimal :max_daily_ag_score
t.datetime :datekey
t.timestamps
end
end
end
|
# These rake tasks to handle sync fields related to ProjectMedia betwwen PG & ES
# 1-bundle exec rails check:project_media:recalculate_cached_field['slug:team_slug&field:field_name&ids:pm_ids']
# This rake task to sync cached field and accept teamSlug and fieldName as args so the sync either
# by team or accros... |
class Author
attr_reader :name
private :name
def initialize(name)
@name = name
end
def save!
File.write "_authors/#{slug}.md", to_s
end
def slug
name.downcase.gsub(" ", "-")
end
private
def to_s
<<~AUTHOR
---
title: "#{name}"
---
AUTHOR
end
end
|
class Declutter < Formula
desc "Find duplicate files and folders"
homepage "https://github.com/ablinov/declutter"
url "https://github.com/ablinov/declutter/archive/0.1.8.tar.gz"
sha256 "5a5109c1ecf83a4b4e569522c9462491a29cd2f5541e075eef4848182efb6661"
def install
args = ["make", "build"]
system *arg... |
class CreateSales < ActiveRecord::Migration
def change
create_table :sales do |t|
t.integer :number, null: false
t.date :date, null: false
t.decimal :total, precision: 12, scale: 2, null: false
t.decimal :discount, precision: 8, scale: 2, null: true
t.references :store, index: true
... |
describe OrderController do
it 'should return ReleaseOrder objects for open releases by default' do
get '/orders'
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result.length).to be 5
end
it 'should return ReleaseOrder objects for all releases when includeClosedReleases param ... |
class Ping < ActiveRecord::Base
enum ping_status: [:success,:failed]
belongs_to :monitoring_session
end
|
require 'rails_helper'
require 'support/path_helper'
include PathHelper
shared_examples 'invalid parameter returns 422' do |object, verb_pair, parameters|
it 'responds with 422', type: :request do
key = user_key(api_key.access_token)
verb_pair.each_pair do |action, request|
path = build_path(object, ac... |
module Deliveryboy
module Plugins
LOADED = {}
def self.included(klass)
LOADED[LOADED[:last_script]] = klass
end
def self.load(script)
LOADED[:last_script] = script
require script
LOADED[script]
end
end
end |
class BootstrapBreadcrumbsBuilder < BreadcrumbsOnRails::Breadcrumbs::Builder
# This is for making the output of the Breadcrumbs on Rails builder compatible
# with Bootstrap.
#
# Code is from here: https://gist.github.com/2400302
#
def render
@context.content_tag(:ul, :class => 'breadcrumb') do
... |
class Product < ActiveRecord::Base
has_many :order_items
has_many :reviews
default_scope { where(active: true) }
end |
require 'generators/chat_shuttle/orm_helpers'
module Mongoid
class ChatShuttleGenerator < Rails::Generators::NamedBase
include ChatShuttle::OrmHelpers
source_root File.expand_path('../templates', __FILE__)
class_option :associate_with, type: :string, default: 'User'
def create_model
@associate... |
require 'test_helper'
require 'bigdecimal'
class ExchangeRateTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::ExchangeRate::VERSION
end
def make_mock_source(date, from_name, from_rate, to_name, to_rate)
mock_source = MiniTest::Mock.new
mock_source.expect :get, BigDecimal.new(... |
class Api::V1::ReferralContactsController < Api::V1::BaseController
before_action :set_referral_contact, only: [:show, :update, :destroy]
def_param_group :referral_contact do
param :referral_contact, Hash, required: true, action_aware: true do
param :phone_number, String, required: true, allow_nil: false... |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :education do
title "MyString"
study_field "MyString"
pursued "MyString"
univercity "MyText"
started "2014-02-15"
finished "2014-02-15"
average 1.5
teacher_id 1
end
end
|
# frozen_string_literal: true
begin
require 'rspec/sleeping_king_studios/matchers/core/deep_matcher'
rescue NameError
# Optional dependency.
end
require 'stannum/constraints/parameters/extra_keywords'
require 'stannum/rspec'
require 'stannum/support/coercion'
module Stannum::RSpec
# Asserts that the command va... |
module Instagram
class Client
# Methods for the Users API.
#
# @see http://instagram.com/developer/endpoints/users/
module Users
# Retrieve a single user's information.
#
# @param user [String, Integer] The user ID or username.
# @return [Hashie::Mash] The user's data.
... |
module ManageIQ::Providers::Amazon::CloudManager::Vm::Operations
extend ActiveSupport::Concern
include_concern 'Guest'
include_concern 'Power'
included do
supports :terminate do
unsupported_reason_add(:terminate, unsupported_reason(:control)) unless supports_control?
end
end
def raw_destroy... |
class UserTag < ActiveRecord::Migration[5.1]
def change
add_reference :user_tags, :user
add_reference :user_tags, :tag
end
end
|
FactoryBot.define do
factory :item do
title {'オーイェー'}
concept {'パーリーピーポー'}
category_id {2}
status_id {3}
delivery_id {2}
area_id {2}
day_id {3}
price {350}
association :user
after(:build) do |item|
item.image.attach(io: File.open('public/apple-touch-icon.png'), filename:... |
=begin
* ****************************************************************************
* BRSE-SCHOOL
* ADMIN - QuestionsController
*
* 処理概要 :
* 作成日 : 2017/09/12
* 作成者 : daonx – daonx@ans-asia.com
*
* 更新日 :
* 更新者 :
* 更新内容 :
*
... |
class Photos::CritiquesController < ApplicationController
before_action :authenticate_user!
def new
@photo = Photo.find(params[:photo_id])
@critique = Critique.new
end
def create
@photo = Photo.find(params[:photo_id])
@profile = current_user.profile
@critique = Critique.new(critique_pa... |
#
# kafka::config_files
#
include_recipe "runit"
include_recipe "kafka::opsworks_hosts"
runit_service "kafka" do
action :nothing
end
install_root_dir = node[:kafka][:install_root_dir]
version_dir = "kafka_#{node[:kafka][:version_scala]}-#{node[:kafka][:version]}"
install_dir = "#{install_root_dir}/#{version_dir}"
... |
class School < ApplicationRecord
has_many :posts
belongs_to :user, optional: true
mount_uploader :image, ImageUploader
end
|
class Splam::Rule
class << self
attr_writer :splam_key
# Global set of rules for all splammable classes. By default it is an array of all Splam::Rule subclasses.
# It can be set to a subset of all rules, or even a hash with specified weights.
# self.default_rules = [:bad_words, :bbcode]
# ... |
ActiveAdmin.register Department do
permit_params :dep_name, :description
controller do
before_action :validate_permitions, only: [:new, :edit, :destroy]
private
def validate_permitions
unless current_user.sistem_manager?
flash[:error] = "You do not have permissions to perform this task"... |
json.array! @poke_locs do |l|
json.extract! l, :pokemon_id, :lat, :lng
json.tol l.tol.to_i
json.extract! l, :key
json.extract! l, :iv_a, :iv_d, :iv_s if l.iv_a
json.extract! l, :weight, :height if l.weight
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
def index_increment
session[:index_counter] = 0 if session[:index_counter... |
require 'spec_helper'
describe Topic do
before(:each) do
@topic = Factory(:topic)
end
it { should validate_presence_of(:title) }
it { should validate_presence_of(:content) }
it { should belong_to(:user) }
it { should have_many(:subscriptions) }
it { should have_many(:subscribers) }
it { should val... |
# ............... Strings II .............
# .............. .split Method ................
sentence = "Hi my name is Adam. There are spaces here!"
puts sentence.split
puts sentence.split(" ")
sentence = "Hi my name is Adam. There are spaces here!"
words = sentence.split(" ")
words.each { |word| puts word.leng... |
class Todo < ActiveRecord::Base
include ActionView::Helpers::DateHelper
belongs_to :user
validates :description, presence: true
default_scope { order('created_at ASC') }
scope :visible_to, ->(user) { user ? where(user_id: params[user_id]) : none }
def expired?
self.created_at <= 7.days.ago
end
def days_... |
# frozen_string_literal: true
require 'choice'
require 'app/version'
Choice.options do
header ''
header 'Specific options:'
option :command do
short '-c'
long '--command=[check,work]'
desc 'The command to execute'
default 'work'
end
option :arguments do
short '-a'
long '--... |
# encoding: utf-8
require 'open-uri'
#require 'nokogiri'
require 'cgi'
class TransactionPdf < Prawn::Document
include ActionView::Helpers::NumberHelper
PAGE_WIDTH = 572
def initialize(transaction)
super(top_margin: 20, left_margin: 20, right_margin: 20, bottom_margin: 20, page_layout: :portrait)
@trans... |
# Solves the classic Towers of Hanoi puzzle.
def hanoi(n,a,b,c)
if n-1 > 0
hanoi(n-1, a, c, b)
end
puts "Move disk %s to %s" % [a, b]
if n-1 > 0
hanoi(n-1, c, b, a)
end
end
i_args=ARGV.length
if i_args > 1
puts "*** Need number of disks or no parameter"
exit 1
end
n=3
if i_args > 0
begin
... |
#
# Cookbook Name:: berkshelf-api
# Recipe:: upstart
#
# Install Upstart script
template 'berks-api.upstart.conf' do
path '/etc/init/berks-api.conf'
owner 'root'
group 'root'
mode '0644'
end
service 'berks-api' do
provider Chef::Provider::Service::Upstart
supports :restart => true, :start => true, :stop =... |
require 'docking_station'
describe DockingStation do
it { is_expected.to respond_to :release_bike }
it "releases a bike" do
bike = Bike.new
subject.dock(bike)
expect(subject.release_bike).to eq bike
end
it { is_expected.to respond_to(:bikes) }
it 'returns docked bikes' do
bike = Bike.new
... |
# -*- encoding : utf-8 -*-
# Klasa zadania wysłania e-maila po dodaniu nowego zgłoszenia
#
# Określa zadanie wykonywane przez plugin +delayed_job+
#
class MailIssueAdded < Struct.new(:issue_instance_id)
# Wywołuje metodę NotificationMailer
def perform
NotificationMailer.issue_added(issue_instance_id)
end
e... |
class AddDummyModelIdInHorses < ActiveRecord::Migration
def change
add_column :horses, :dummy_model_id, :integer
end
end
|
include DataMagic
Given(/^a CVV user with "([^"]*)" in Service Platform logs in$/) do |user_type|
cvv_user_login user_type.downcase.gsub(" ", "_")
end
And(/^the login page displays the message "([^"]*)"$/) do |error_message|
expect(on(UserLoginPage).error_message_element.text).to eq error_message
end |
class TrainingSubmission < ActiveRecord::Base
acts_as_paranoid
include Rails.application.routes.url_helpers
include Sbm
# current_step starts from 1, not 0
attr_accessible :current_step, :open_at, :std_course_id, :submit_at, :training_id
belongs_to :std_course, class_name: "UserCourse"
belongs_to :trai... |
require 'mini_magick'
require 'digest/md5'
class Identicon
Tobyte = Struct.new(:name, :byte_array, :color_byte, :grid, :markPoint)
def initialize(user_name, path)
if user_name.nil? || user_name.empty?
@user_name = "unknown"
else
@user_name = user_name
end
if path.nil? || path.empty?
... |
class Game
def initialize
@frames = []
@current_frame = []
end
def roll(pins)
validate_roll(pins)
@current_frame << pins
if @frames.size < 9
if @current_frame == [10] || @current_frame.sum == 10 || @current_frame.size == 2
@frames << @current_frame
@current_frame = []
end
... |
# frozen_string_literal: true
require 'helper'
require 'peddler/headers'
class TestPeddlerHeaders < MiniTest::Test
include ::Peddler::Headers
attr_reader :headers
def setup
@headers = {
'x-mws-quota-max' => '200.0',
'x-mws-quota-remaining' => '200.0',
'x-mws-quota-resetsOn' => '2017-01-3... |
require 'hashie/mash'
class Category < Hashie::Mash
def has_code?(code)
code == self.code
end
def to_param
code
end
def short_name
self.fetch(:short_name, compute_short_name)
end
private
def compute_short_name
self.name.split(' ').first
end
end
|
module Hippo::TransactionSets
module HIPAA_837
class L2000B < Hippo::TransactionSets::Base
loop_name 'L2000B' #Subscriber Hierarchical Level
#Subscriber Hierarchical Level
segment Hippo::Segments::HL,
:name => 'Subscriber Hierarchical Level',
:minim... |
class CreateContracts < ActiveRecord::Migration[6.0]
def change
create_table :contracts do |t|
t.date :start_day , null: false
t.date :finish_day , null: false
t.integer :price , null: false
t.references :company , null: false , foreign_key: true
t.references :temporary , null: false... |
class Person
attr_accessor :name
def initialize(name)
@name = name
end
def greet
puts "Hi, my name is #{@name}"
end
end
class Student < Person
def learn
puts "I get it!"
end
end
class Instructor < Person
def teach
puts "Everything in Ruby is an Object"
end
end
# end of classes ... |
class HostessesController < ApplicationController
before_action :signed_in_administrator, only:
[:new, :index, :edit, :update, :destory]
def new
@hostess = Hostess.new
end
def index
@hostesses = Hostess.where(lang: I18n.locale)
end
def create
@hostess = Hostess.new(hostess_params)
... |
describe Client do
describe '#send_event' do
context 'without arguments' do
let(:payload) { { ref: nil, repository: { name: nil } } }
it 'builds and sends a payload' do
expect(subject).to receive(:send_payload).with(:push, payload)
subject.send_event
end
end
context 'wi... |
require 'rails_helper'
RSpec.describe Seller do
before(:each) do
@store = FactoryBot.create(:store)
@seller = Seller.create(name: FFaker::Name.name, store: @store)
end
context "be valid" do
it "with all params" do
expect(@seller).to be_valid
end
end
context "not be valid" do
it "w... |
# @param {Integer[]} candies
# @param {Integer} extra_candies
# @return {Boolean[]}
def kids_with_candies(candies, extra_candies)
max_candy = candies.max
result = []
candies.each do
|candy|
if candy + extra_candies >= max_candy
result << true
else
result << false
end
end
result
end... |
class Condition < ApplicationRecord
belongs_to :wrap
validates :weight, numericality: { greater_than: 0, message: "は'0'以上でご入力ください"}
validates :temperature, numericality: { greater_than: 0, message: "は'0'以上でご入力ください" }
end
|
#encoding: utf-8
module MembersHelper
def display_subscription_files_actions subscription
links = []
if subscription.documents.any?
links << '<div class="btn-group">'
subscription.documents.each do |doc|
links << "#{link_to raw("<i class='icon-download'></i>"), doc.nice_file.url, class: "b... |
module CompaniesHouseXmlgateway
module Service
class ChargeRegistration < CompaniesHouseXmlgateway::Service::FormChargeRegistration
API_CLASS_NAME = 'ChargeRegistration'
SCHEMA_XSD = 'http://xmlgw.companieshouse.gov.uk/v1-0/schema/forms/ChargeRegistration-v2-9.xsd'
def build(submission)
... |
class Api::MailboxesController < ApplicationController
respond_to :json
before_filter :authorized?
def index
respond_with(@mailboxes = current_account.mailboxes.all)
end
end
|
require 'spec_helper'
describe TaxonRelationship do
context "when hybrid" do
let(:parent){
create_cites_eu_genus(
:taxon_name => create(:taxon_name, :scientific_name => 'Lolcatus')
)
}
let!(:tc){
create_cites_eu_species(
:parent_id => parent.id,
:taxon_name => cr... |
# frozen_string_literal: true
module Liquid; class Tag; end; end
module Jekyll
class Avatar < Liquid::Tag
VERSION = "0.4.2".freeze
end
end
|
require 'test_helper'
class FundingSourcesControllerTest < ActionDispatch::IntegrationTest
setup do
@funding_source = funding_sources(:one)
end
test "should get index" do
get funding_sources_url
assert_response :success
end
test "should get new" do
get new_funding_source_url
assert_resp... |
require 'yt/collections/base'
require 'yt/models/status'
module Yt
module Collections
# @private
class Statuses < Base
private
def attributes_for_new_item(data)
{data: data['status']}
end
# @return [Hash] the parameters to submit to YouTube to get the status
# of a re... |
class Ability
include CanCan::Ability
def initialize(user)
@user = user
@user ||= User.new
clear_aliased_actions # clear all defaults
alias_action :index, :show, to: :read # restore this default
alias_action :new, to: :create # restore this default
# Note that this default is still cleared... |
class Profile < ActiveRecord::Base
belongs_to :user
has_many :photos
has_many :critiques
has_many :photos, through: :critiques
validates_presence_of :first_name, :last_name, :location, :country
def country_name
country_name = ISO3166::Country[country]
country_name.translations[I18n.locale.to_... |
# This method takes n arrays as input and combine them in sorted ascending order
# Improves the space complexity
# I made time and space improvements in version two by removing the extra array "sorted_array" while implementing merge sort.
|
class AddUpdatedByIdToListingChanges < ActiveRecord::Migration
def change
add_column :listing_changes, :updated_by_id, :integer
end
end
|
require 'rails_helper'
describe MembershipsController do
let(:admin) { create_user2(admin: true) }
let(:non_member) { create_user2 }
let(:project) { create_project }
let(:member) { create_user2 }
let(:membership) { create_membership(member, project) }
describe 'DELETE #destroy' do
it "Does not allo... |
module ApplicationHelper
def active?(path)
"active" if current_page?(path)
end
def image_generator(height:, width:)
"http://via.placeholder.com/#{width}x#{height}"
end
def img img, type
if img.model.has_attribute?(:main_image)
if img.model.main_image?
return img
end
elsif ... |
FactoryGirl.define do
factory :answer, class: Answer do
association :question, factory: :question
answer_type "yellow"
trait :for_plan do
sequence(:answer_type) {|n| n}
sequence(:text){|n| "texto-random#{n}" }
end
end
end
|
class TasksController < ApplicationController
before_action :set_task, only: %i[edit update destroy]
before_action :set_data, only: %i[new edit]
def index
@tasks = Task.order(created_at: :desc).paginate(page: params[:page], per_page: 10)
end
def new
@task = Task.new
end
def create
task = Ta... |
namespace :git do
desc "to checkout into an existing branch, rake git:checkout['message'] BRANCH=branch_name"
task :checkout, [:commit_message] => [:status, :add, :commit, :checkout_branch, :current_branch] do |t, args|
end
desc "to checkout and merge, rake git:checkout_and_merge['commit message'] BRANCH=bra... |
class ChangeRestaurantRatingColumn < ActiveRecord::Migration
def change
change_column :restaurants, :rating, :decimal, precision: 2, scale: 1
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.define :streama do |streama|
streama.vm.box = "bento/centos-7"
streama.vm.hostname = "streama"
streama.vm.network :public_network,:bridge=>"eth0"
config.vm.provision "shell", inline: <<-SHELL
yum in... |
class Admin::NavNodesController < AdminController
def create
@nav_node = NavNode.new(params[:nav_node])
respond_to do |format|
if @nav_node.save
format.json { render json: @nav_node, status: :created, location: admin_nav_node_path(@nav_node) }
else
format.json { render json: @... |
class Dessert
def initialize(name, calories)
@name, @calories = name, calories.to_i
end
def name=(value)
@name = value
end
def name
@name
end
def calories=(value)
@calories = value
end
def calories
@calories
end
def healthy?
... |
class AddOriginboardidToSprint < ActiveRecord::Migration[6.0]
def change
add_column :sprints, :originBoardId, :string
end
end
|
require 'rails_helper'
RSpec.describe 'admin - searching for accounts', :js do
include_context 'logged in as admin'
let!(:account) { create_account }
before { visit root_path }
# there doesn't seem to be a way to simulate an 'enter' hit natively
# with capybara, so we have to trigger the form submit using J... |
# frozen_string_literal: true
# Http requests for all mailers
class MailersController < ApplicationController
before_action :fetch_business, only: %i[create destroy]
def create
if MailerBuilder.new(*builder_params).build!
flash[:notice] =
"#{params[:type].humanize} mailer sent to #{@business.com... |
require 'legacy_migration_spec_helper'
describe NoteMigrator do
before :all do
any_instance_of(WorkfileMigrator::LegacyFilePath) do |p|
# Stub everything with a PNG so paperclip doesn't blow up
stub(p).path { File.join(Rails.root, "spec/fixtures/small2.png") }
end
NoteMigrator.migrate('workf... |
require 'rails_helper'
RSpec.describe "V1::Invitees", type: :request do
describe '#create' do
context 'when the user has an account (email is upcase)' do
let(:project) { create(:project) }
let(:user) { create(:user) }
let(:valid_user) { { user: { email: user.email.upcase } }.to_json }
bef... |
class Questionnaire < ApplicationRecord
has_many :questionnaire_responses
enum questionnaire_type: {
monthly_screening_reports: "monthly_screening_reports",
monthly_supplies_reports: "monthly_supplies_reports",
drug_stock_reports: "drug_stock_reports"
}
validates :dsl_version, uniqueness: {
sc... |
describe Player do
let(:player_1) { Player.new("Bob") }
let(:player_2) { Player.new("Mark") }
HP = 60
describe '#name' do
it 'returns the player name' do
expect(player_1.name).to eq("Bob")
end
end
end
|
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
has_many :reviews
has_many :books, through: :reviews
end
|
require 'rubygems'
require 'bundler/setup'
Bundler.require(:default)
class FileHandler
attr_reader :file_array
attr_reader :warning
def initialize(file_path)
file = File.new(file_path)
filename = File.basename(file_path)
file_array = []
file.readlines.each_with_index.map do |line, index|
... |
require 'test_helper'
class Manage::ProductCatesControllerTest < ActionDispatch::IntegrationTest
setup do
@manage_product_cate = manage_product_cates(:one)
end
test "should get index" do
get manage_product_cates_url
assert_response :success
end
test "should get new" do
get new_manage_produc... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user, :current_admin?, :order_auth?
before_action :build_cart
def current_user
if session[:user_id]
@current_user ||= User.find(session[:user_id])
end
end
def current_admin?
... |
require 'rubygems'
require 'fakeweb'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'tmdb_party'
def fixture_file(filename)
return '' if filename == ''
file_path = File.expand_path(File.dirname(__FILE__) + '/fixtures/' + filename)
File.read... |
module DeviseHelper
def devise_error_messages!
return '' if resource.errors.empty?
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
render 'app/views/layouts/devise'
end
end
|
require 'spec_helper'
describe Killbill::Plugin::ActiveMerchant::Gateway do
it 'should honor configuration options' do
gateway_builder = Proc.new {}
logger = Logger.new(STDOUT)
config = {}
verify_config
::Killbill::Plugin::ActiveMerchant::Gateway.wrap(gateway_builder, logger,... |
module Globase
class ListProfilesSearch < NestedResource
class << self
def search(parent, criteria = {}, expand = "Profile", force_deferred = false, params = {})
send_request( parent,
:post,
params.merge(force_deferred: force_deferred, expand: expand),
... |
# coding: utf-8
class HomeController < ApplicationController
layout 'atuservicio'
def index
# Get the ProviderMaximum object which contains all the maximum
# values to compare in the graphs in the home view.
@provider_maximums = ProviderMaximum.first
@title = 'Inicio'
@description = 'Toda la i... |
require 'test_helper'
class ProjectareasControllerTest < ActionController::TestCase
setup do
@projectarea = projectareas(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:projectareas)
end
test "should get new" do
get :new
assert_respon... |
# Exercises: Easy 1
# Question 1. What would you expect the code below to print out?
numbers = [1, 2, 2, 3]
numbers.uniq
puts numbers
# outputs
# 1
# 2
# 2
# 3
# it doesn't mutate the object so it stays the same
# Question 2. Describe the difference between ! and ? in Ruby.
# And explain what would happen in the... |
class Employee < ActiveRecord::Base
attr_accessible :firstname, :lastname, :account_number, :rate, :hours_week, :worked_hours
validates_presence_of :firstname, :lastname, :account_number, :rate, :hours_week
validates_uniqueness_of :account_number
validates :account_number, format: {
with: /^?[0-9]{16}/,
... |
describe Pantograph do
describe Pantograph::PantFile do
describe "min_pantograph_version action" do
it "works as expected" do
Pantograph::PantFile.new.parse("lane :test do
min_pantograph_version '0.1'
end").runner.execute(:test)
end
it "raises an exception if it's an o... |
class LtiLaunchesController < ApplicationController
include CanvasSupport
include LtiSupport
layout "client"
skip_before_action :verify_authenticity_token
before_action :debug_data
before_action :check_disabled
before_action :do_lti
before_action :set_lti_launch_values
def index
if current_appl... |
class V1::MenusController < ApplicationController
before_action :set_menu, only:[ :update, :delete, :show ]
def index
menus = Menu.all
render json: { result: true, menu: menus }, status: :ok
end
def show
render json: { result: true, menu: @menu }
end
def create
... |
require 'fileutils'
namespace :assets do
desc 'Moves static, compiled html pages from /public/assets to /public'
task :static_pages => [:precompile] do
Dir.glob("#{Rails.public_path}/assets/*.html") do |file|
name = file.match(/([a-zA-Z0-9]*)-/)[1] + ".html"
FileUtils.cp file, "#{Rails.public_path}... |
class DynamicSchemaImporter
class NotesRow < ObjectRow
def field_valid?
true
end
def grouping_name
DEFAULT_GROUPING_NAME
end
def fields
[{ name: 'Notes', value_type: 'text' }]
end
def picker_options
[]
end
end
end
|
require_relative "Enumerable"
describe "my_each" do
a = [ "a", "b", "c" ]
it "has the same output as each" do
expect(a.my_each {|x| print x}).to eq(a.each {|x| print x})
end
it "iterate through every element in a array" do
expect(a.my_each {|x| print x}).to eq(["a", "b", "c"])
end
end
de... |
require 'test_helper'
class SessionTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the object graph must be correctly connected" do
session = sessions(:session_one)
assert session.date.instance_of?(Date)
assert session.interventions.length == 1
assert session.interventio... |
require 'reloader/sse'
class BrowserController < ApplicationController
include ActionController::Live
def index
# SSE expects the `text/event-stream` content type
response.headers['Content-Type'] = 'text/event-stream'
sse = Reloader::SSE.new(response.stream)
begin
i = 0
loop do
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.