text stringlengths 10 2.61M |
|---|
class Building < ApplicationRecord
has_many :apartments, dependent: :destroy
accepts_nested_attributes_for :apartments,
allow_destroy: true,
reject_if: proc {|attributes| attributes['number'].blank?}
def to_s
name
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{redmine_charts}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :req... |
require "socket"
module Sysloggly
module Clients
class Networklog
attr_reader :input_uri, :socket
# Creates a new client that conforms to the Logger::LogDevice specification.
#
# @return [Sysloggly::Client::Networklog]
# @api public
def initialize(input_uri)
@input_ur... |
# 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' }])
# Ch... |
class ChecksController < ApplicationController
before_action :move_to_index, except: :index
def index
@checks = Check.includes(:user).page(params[:page]).per(4).order("created_at DESC")
end
def new
@question1 = Question.where( category:1).order("RAND()").limit(1).map{|v| v.text}
@question2... |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# first_name :string(255)
# last_name :string(255)
# email_address :string(255)
# password :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
clas... |
class Subject < ActiveRecord::Base
has_and_belongs_to_many :qualifications
default_scope { order('title ASC') }
validates :uuid, :presence => true, :uniqueness => true
end
|
class VideoFile < ActiveRecord::Base
belongs_to :media, polymorphic: true
attr_accessible :path
attr_accessible :created_at
before_validation :attributes_from_path
before_save :update_watched
validates_presence_of :path
validates_presence_of :extension
validates_uniqueness_of :path
EXTENSIONS ... |
class InstitutionsController < ApplicationController
before_action :require_medusa_user
before_action :find_institution, only: [:show, :edit, :update, :destroy]
def index
authorize! :read, Institution
@institutions = Institution.order(:name).all
end
def new
authorize! :create, Institution
@i... |
class EligibilityService
OUTPUT ={ customer_eligible: 'Customer is eligible',
customer_ineligible: 'Customer is not eligible',
technical_failure: 'Service technical failure',
invalid_account_number: 'The supplied account number is invalid'
}
end |
#!/Users/spamram/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
# Goal:
# Find the product abc where a+b+c = 1000 and {a, b, c} is a
# pythagorian triplet.
def is_triplet?( a, b, c )
(a*a + b*b) == (c*c)
end
def trip2
1.upto(1000) do |i|
i.upto(1000 - i) do |j|
j.upto(1000 - i - j) do |k|
return i*j*... |
require 'amberbit-config'
module AmberbitConfig
class Engine < ::Rails::Engine
engine_name :amberbit_config
# Try to initialize AppConfig as soon as possible
initializer 'amberbit_config.initialize_config', before: :load_environment_config do |app|
AmberbitConfig.initialize_within app.root.join('c... |
class EasyIssueTimer < ActiveRecord::Base
belongs_to :user
belongs_to :issue
validates :user_id, :issue_id, :presence => true
default_scope(order(:start))
scope :running, lambda { where(:end => nil) }
def self.active?(project=nil)
scope = EasySetting.where(:name => 'easy_issue_timer_settings')
... |
require 'set'
module Spider
class Page
RESERVED_COOKIE_NAMES = /^(?:Path|Expires|Domain|Secure|HTTPOnly)$/i
def cookie
@response['Set-Cookie'] || ''
end
alias raw_cookie cookie
def cookies
(@response.get_fields('Set-Cookie') || [])
end
def cookie_params
params = {}... |
# -*- coding: utf-8 -*-
=begin
=end
require './Manejador'
class Cesar
TEXTO_LIMPIO = "texto_limpio.txt"
CESAR_EN = "texto_cifrado_cesar"
CESAR_DES = "texto_cesar_desencriptado"
@texto = nil
@manejador = nil
## Crea una instancia de la clase Cesar, la cual se encarga de
# leer un archivo y limpiarlo de... |
module ChainReactor
require 'reactor'
# Error raised when there's a error parsing the chain file.
#
# This contains the original exception raised by eval().
class ChainfileParserError < StandardError
attr_reader :original
def initialize(original)
@original = original
super(original.messa... |
class AcademicLevel < ActiveRecord::Base
attr_accessible :name, :question_type_id, :published, :ussd_id
# Relationships
belongs_to :question_type
has_many :sessions
end
|
class Tweet < ApplicationRecord
validates :content, presence: true, length: { in: 1..140 }
mount_uploader :image, ImageUploader
end
|
# frozen_string_literal: true
class Trophy < ApplicationRecord
# trophy categories
enum trophy_category: { collected_coins: 0, killed_monsters: 1,
times_of_death: 2, killed_turtles: 3, killed_bowsers: 4 }
# associations
has_many :trophy_users, dependent: :destroy
has_many :users, through: :trophy_users
... |
# lib/tb/ex_enumerable.rb - extensions for Enumerable
#
# Copyright (C) 2010-2012 Tanaka Akira <akr@fsij.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above... |
class CreateHierarchyElements < ActiveRecord::Migration[5.1]
def change
create_table :hierarchy_elements do |t|
t.string :name, null: false
t.integer :visibility, null: false, default: 0, index: true
t.text :description, null: true
t.timestamps
end
add_reference :hier... |
class Spot < ApplicationRecord
has_and_belongs_to_many :wind_directions, dependent: :destroy
has_and_belongs_to_many :wave_directions, dependent: :destroy
belongs_to :wfinder
has_rich_text :content
validates :label, presence: true
validates :sport, presence: true
accepts_nested_attributes_for :wfinder
... |
require 'rails_helper'
RSpec.describe "books/edit", type: :view do
before(:each) do
@book = assign(:book, Book.create!(
:name => "MyString",
:author => "MyString",
:year => 1,
:category_id => Category.create!(:name => "History").id
))
@categories = assign(:categories, Category.all... |
class TestsController < ApplicationController
def index
@tests = Test.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @tests }
end
end
def show
@test = Test.find(params[:id])
respond_to do |format|
format.html # show.html.erb
form... |
describe Reservations::UseCases::Update do
let(:call_class) do
described_class.new(
params: { args: {
cinema_id: Cinemas::Model.last.id,
movie_id: Movies::Model.last.id,
screening_id: Screenings::Model.last.id,
seat_ids: [{ seat_id: Seats::Model.first.id }]
},
... |
# frozen_string_literal: true
FactoryBot.define do
factory :seats_reservation do
row { 'A' }
seat_number { 5 }
reservation
cinema_hall
end
end
|
class EbayAPI
scope :sell do
scope :fulfillment do
scope :orders do
operation :list do
option :order_ids, optional: true
option :filter, optional: true
option :limit, optional: true
option :offset, optional: true
http_method :get
query... |
class AddResidenceToPlayers < ActiveRecord::Migration[5.1]
def change
add_column :players, :residence, :string
end
end
|
class Skill < ActiveRecord::Base
belongs_to :ability
attr_accessible :category, :level, :specialisation
def score
ability.level + level
end
end
|
module ReviewsHelper
ResultType = Struct.new(:id,:name)
ReviewType = Struct.new(:id,:name)
ReviewResultImg = ["/images/icons/edit_remove ----.png",
"/images/icons/button_ok.png",
"/images/icons/button_cancel.png",
"/images/icons/file_broken.png"]
... |
class DadoscadastraisController < ApplicationController
layout 'painel'
before_action :logged_in?
def index
flash[:notice] = nil
flash[:alert] = nil
@user = Usuario.find_by(id: session[:user_id])
end
def update
valores = params.require(:usuario).permit(:nome_completo,:celular,:telefone... |
class RegistrantUser < User
ACCEPTED_ISSUER = 'AS Sertifitseerimiskeskus'.freeze
attr_accessor :idc_data
devise :database_authenticatable, :trackable, :timeoutable
def ability
@ability ||= Ability.new(self)
end
delegate :can?, :cannot?, to: :ability
def ident
registrant_ident.to_s.split('-').la... |
require_relative 'helper'
describe Recaptcha::Configuration do
describe "#api_server_url" do
it "serves the default" do
Recaptcha.configuration.api_server_url.must_equal "//www.google.com/recaptcha/api.js"
end
it "servers the default for nil" do
Recaptcha.configuration.api_server_url(ssl: ni... |
# Encoding: UTF-8
require 'test_helper'
require 'traject/marc_reader'
require 'marc'
describe "Traject::MarcReader" do
it "reads XML" do
file = File.new(support_file_path "test_data.utf8.marc.xml")
settings = Traject::Indexer::Settings.new("marc_source.type" => "xml")
reader = Traject::MarcReader.new(... |
class Vehicle < ApplicationRecord
@colors = [
'Branco',
'Preto',
'Prata',
'Vermelho',
]
validates :plate,presence: true,
length: { is: 8 },
format: { with: /\A[a-zA-Z]{3}\-\d{4}\z/}
#/\Aimage\/.*\z/
validates :year,presence: true,
... |
require './app.rb'
describe Data::Fetcher do
let(:scanner) { Data::Scanners::BestNewsScanner.new }
context "Init fetcher" do
it "Init a fetcher object" do
obj = Data::Fetcher.new
expect(obj).to be_a(Data::Fetcher)
end
end
context "fetcher methods" do
let(:obj) { Data::Fetcher.new }
... |
# require 'FIle'
class User < ActiveRecord::Base
has_many :articles
validates :username, uniqueness: true
def save_header_image(upload)
name = upload.original_filename
directory = "upload/public/data"
path = File.join(directory, name)
puts name
puts path
puts upload.class
p... |
class CreateMembers < ActiveRecord::Migration[5.1]
def change
create_table :members do |t|
t.integer :near_node_id, null: false
t.integer :far_node_id, null: false
t.timestamps
end
add_index :members, :near_node_id
add_index :members, :far_node_id
end
end
|
class AddReference < ActiveRecord::Migration
def change
add_reference :reports, :user, index: true
add_reference :reports, :spot, index: true
add_reference :counties, :state, index: true
add_reference :cities, :county, index: true
add_reference :zips, :city, index: true
add_reference :spots,... |
class Source < ActiveRecord::Base
has_many :tracks
validates :name, :root_path, presence: true, uniqueness: true
end
|
require 'rails_helper'
feature 'pairng with instances of food' do
it 'start using the site immediately' do
visit('/')
expect(page).to have_button("Start pairing!")
end
it 'create a new empty pairing' do
visit('/pairings/new')
expect{ click_button('Start pairing!') }.to change{Pairing.count}.by ... |
require 'tempfile'
module CurseClient
class Downloader
class DownloadError < StandardError; end
def fetch(uri, path, &block)
HTTP.get(uri) do |response|
case response
when Net::HTTPSuccess
save_response(response, path, &block)
when Net::HTTPRedirection
url ... |
#!/usr/bin/ruby
#
# Copyright 2022 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
class Api::ServiceCategoriesController < ApplicationController
respond_to :json
def index
respond_with ServiceCategory.all,
only: [:_id, :title, :slug],
methods: [:slug]
end
end
|
#!/usr/bin/env ruby
# Print numbers between 45 to 4578 without repeating digits.###
# Ex: 45-ALLOWED;55(repeatng digits)(-NOT ALLOWED. Frnd tld ths 2 me.he tried diff concepts but interviewer wanted an OPTIMAL ONE..LETS C WHO WRITE THIS WITH SIMPLE LOGIC..
# ref: http://www.careercup.com/page?pid=software-engineer-i... |
require File.expand_path('../spec_helper', __FILE__)
require "solrmarc_wrapper"
require 'logger'
describe SolrmarcWrapper do
before(:all) do
@solrmarc_wrapper = SolrmarcWrapper.new(@@settings.solrmarc_dist_dir, @@settings.solrmarc_conf_props_file, @@settings.solr_url)
end
it "retrieves the SolrInputDoc... |
class AlbumSongsController < ApplicationController
before_action :set_album_song, only: [:show, :update, :destroy]
# GET /album_songs
def index
@album_songs = AlbumSong.all
render json: @album_songs
end
# GET /album_songs/1
def show
render json: @album_song
end
# POST /album_songs
def ... |
require_relative 'triple_storage'
module OpenBEL
module Storage
class CacheProxy
include TripleStorage
def initialize(real_storage, cache)
if !real_storage or !real_storage.respond_to?(:triples)
fail ArgumentError, "real_storage is invalid."
end
if !cache or !cache.... |
#encoding: utf-8
require 'spec_helper'
describe "SaldoBancarioHistoricos" do
describe "GET /saldos_bancario_historico" do
it "works! (now write some real specs)" do
# Run the generator again with the --webrat flag if you want to use webrat methods/matchers
get saldos_bancario_historico_path
re... |
class Piece
def initialize(color, board, pos)
@color = color
@board = board
@pos = pos
end
def color
@color
end
def board
@board
end
def pos
@pos
end
def to_s #rook.to_s == rook? , get into the ins var's an... |
class User < ActiveRecord::Base
has_many :tweets
has_secure_password
def slug
self.username.gsub(/[!?,'." "]/, '-').downcase
end
def self.find_by_slug(slug_name)
User.all.detect {|user| user.slug == slug_name}
end
end
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'kubernetes-deploy/render_task'
require 'kubernetes-deploy/options_helper'
require 'kubernetes-deploy/bindings_parser'
require 'optparse'
template_dir = []
bindings = {}
ARGV.options do |opts|
parser = KubernetesDeploy::BindingsParser.new
opts.on("--bind... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BalanceSerializer do
let(:usr) { instance_double('User') }
let(:balance) { Balance::Wrapper.new(usr, '41') }
subject { described_class.new balance }
describe '#balance' do
it 'delegates balance' do
expect(subject.balance).to eq('41'... |
class AddUserNametoUcomments < ActiveRecord::Migration
def self.up
add_column :ucomments, :user_name, :string
end
def self.down
remove_column :ucomments, :user_name, :string
end
end
|
class Image < ApplicationRecord
has_many :ideas, through: :idea_images
has_many :idea_images
end
|
class WebController < ApplicationController
def index
@classifications = Classification.order("popularity").limit(10)
end
def explorer
result = { :categories => {}}
c = params[:id].present? ? Classification.find(params[:id]) : Classification.first
result[:title] = c.title
result[:popularity] ... |
class Article < ApplicationRecord
validates :publish_date, presence: true
validates :record_id, presence: true, uniqueness: true
validates :tag, presence: true
scope :stories, -> { where(tag: 'story') }
scope :comments, -> { where(tag: 'comment') }
scope :from_date, ->(date) { where('publish_date::date = ?... |
require_relative 'station'
class OysterCard
attr_reader :balance, :entry_station, :exit_station, :journey_log
MAX_AMOUNT = 90
def initialize
@balance = 0
@journey_log = []
end
def top_up(amount)
value = @balance + amount
raise "Cannot exceed #{MAX_AMOUNT}" if value > MAX_AMOUNT
@balanc... |
require './lib/seat'
require './lib/row'
class Row
attr_reader :seats
def initialize
@seats = Array.new(50) {|i| i = Seat.new}
end
def available_seats
@available_seats = @seats.reject { |s| !s.available? }.count
end
def book_seats(first_seat, last_seat)
@seats[first_seat..last_seat].each {... |
module TestScript
# class Feature
# attr_reader :req_id, :title, :narrative, :sub_sections, :parent_section
#
# def add_subsection child
# @sub_sections[child.req_id] = child
# end
# end
class Section
attr_reader :section_id, :sub_sections
attr_accessor :title, :narrative, :parent_section
... |
class Endereco < ApplicationRecord
belongs_to :cidade
validates :rua, :bairro, :numero, presence: true
validates :rua, :bairro, :numero, uniqueness: true
end
|
require "spec_helper"
RSpec.describe Player do
let(:player1) { Player.new("Zach Stone", "Pitcher", "Astros") }
let(:player2) { Player.new("Zero Volts", "Shortstop", "Red Sox") }
describe ".new" do
it "take in a name, position, and team_name" do
expect(player1.name).to eq "Zach Stone"
expect(play... |
class App::Api::RoomsController < App::Api::BaseController
def show
room = Room.find(params[:id])
render json: room, serializer: App::Api::RoomSerializer
end
def index
if params[:unit_filter] && params[:capacity_filter]
coworking_unit = CoworkingUnit.find(params[:unit_filter])
rooms = fil... |
require 'spec_helper'
RSpec.describe DesignByContract do
include_context :example_class
before { DesignByContract.forget_contract_specifications! }
describe '.as_dependency_injection_for' do
subject(:on_contract) { described_class.as_dependency_injection_for(example_class, arguments_specification) }
... |
# frozen_string_literal: true
class ReminderJob < ApplicationJob
queue_as :default
def perform(object)
UserMailer.with(object: object).reminder_email.deliver_now
# We can add multiple notification methods here:
# SMS
# Push Notifications (with firebase for example)
# Whatsapp integration
#... |
class FavoritesController < ApplicationController
def list
@favorites = Favorite.all
render("favorite_templates/list.html.erb")
end
def details
@favorite = Favorite.where({ :id => params.fetch("id_to_display") }).first
render("favorite_templates/details.html.erb")
end
def user_favorites
... |
class Cycle < ActiveRecord::Base
belongs_to :device
attr_accessible :device_id, :started, :stopped
def duration
(self.stopped || Time.now.to_i) - self.started
end
def bounded_duration(lower, upper)
# Check if we are outside the range
unless self.started > upper or (self.stopped and sel... |
module Owner
extend ActiveSupport::Concern
included do
# has_many :mailtemplates
has_many :owner_thing_relations, as: :thingable
has_many :events, through: :owner_thing_relations, source: :ownable, source_type: 'Event'
end
end
|
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem 'rails'
gem 'puma'
gem 'pg'
gem 'sass-rails'
gem 'uglifier'
gem 'mini_racer', platforms: :ruby
gem 'coffee-rails'
gem 'devise'
gem 'active_model_serializers'
# gem 'turbolinks', '~> 5'
# Use Redis adapter to run Action C... |
class BagsController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :set_bag, only: %i[ show edit update destroy ]
before_action :logged_in?, except: %i[create]
helper_method :checkout
# GET /bags or /bags.json
def index
@bags = Bag.all
end
def cart
@bags =... |
class Api::UsersController < ApplicationController
skip_before_action :verify_authenticity_token
def index
render json: User.all
end
def create
@user=User.new(user_params)
if @user.save
render json: {
status: 200,
message: "Successfully created the user",
User: @user
}.to_json
else
rend... |
require 'nokogiri'
require 'uri'
RSpec::Matchers.define :usps_param do |css, expected|
def parse_xml(url)
uri = URI(url)
array = uri.query.
split('&').
map{|pair| pair.split('=', 2)}
hash = Hash[array]
encoded_xml = hash['XML']
xml = URI.unescape(encoded_xml)
Nokogiri::XML(xml)... |
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "rails_admin_phone_number_field/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "rails_admin_phone_number_field"
s.version = RailsAdminPhoneNumberField::VERSION
s.auth... |
require "test_helper"
class UserFlowsTest < ActionDispatch::IntegrationTest
setup do
Capybara.current_driver = Capybara.javascript_driver # :seleniun by default
#Capybara.javascript_driver = :poltergeist
end
def set_avatar(file_route = "app/assets/images/missing.png")
attach_file "user_avatar", Fil... |
class Inventory < ActiveRecord::Base
belongs_to :order_line
has_one :donation_line
has_one :donation, through: :donation_line
has_one :order, through: :order_line
end |
# == Schema Information
#
# Table name: used_jokes
#
# id :bigint(8) not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# all_joke_id :bigint(8)
# campaign_id :bigint(8)
#
# Indexes
#
# index_used_jokes_on_all_joke_id (all_joke_id)
# index_use... |
class PostsController < ApplicationController
before_action :set_post_params, only: [:show, :edit, :update, :destroy]
before_action :require_user, except: [:index, :show] #shut down routes if a user isn't logged in
before_action :must_be_creator, only: [:edit, :update, :destroy]
def index
@posts = Post.... |
class User < ActiveRecord::Base
has_many :cats
has_many :cat_rental_requests
has_many :session_keys
validates :username, :password_digest, presence: true
validates :password, length: { minimum: 6, allow_nil: true }
validates :username, uniqueness: true
attr_reader :password
def self.find_by_credential... |
class ProjectsController < ApplicationController
before_action :authenticate_user!
after_action :verify_authorized
def index
@projects = Project.published
authorize @projects
@projects = @projects.order(created_at: :desc).include_user
end
def show
@project = Project.find(params[:id])
aut... |
class RemoveCidAndFormatFromSong < ActiveRecord::Migration
def change
remove_column :songs, :cid, :string
remove_column :songs, :format, :integer
end
end
|
# Feature: Company page
# As a visitor
# I want to visit a company page
# So I can see it job offers
feature 'Job page' do
# Scenario: Visitor can see any company
# Given I am a visitor
# When I visit a company
# Then I see it job offers
scenario 'visitor sees company page' do
company = Facto... |
class PackagesController < ApplicationController
def index
# @packages = Package.all
@packages = Package.all.order('created_at DESC')
# same as first line but sort in descending (DESC) order
# based on what time they were created
end
def new
@package = Pac... |
require 'yt/collections/base'
require 'yt/models/branding_setting'
module Yt
module Collections
# @private
class BrandingSettings < Base
private
def attributes_for_new_item(data)
{data: data['brandingSettings']}
end
# @return [Hash] the parameters to submit to YouTube to get ... |
require 'test_helper'
class ArtColonyTest < ActiveSupport::TestCase
def setup
@art_colony = ArtColony.new
end
test "should not be valid without name" do
@art_colony.name = nil
@art_colony.name = "lorem ipsum"
assert_not @art_colony.valid?
end
test "should not be valid without info" do
@... |
class Item < ApplicationRecord
enum kind: [ :food, :drink]
validates :title, presence: true
validates :price, presence: true, numericality: { greater_than: 0}
end
|
name = "Palindrome"
content = "Detect whether a string is a palindrome."
test_cases = [["\"hello world\"", false], ["\"taco cat\"", true], ["\"racecar\"", true]]
format = :bullet
q = Question.create(name: name, content: content, test_cases: test_cases, format: format)
name = "Line Items"
content = "Return the line it... |
class Product < ApplicationRecord
has_many :reviews
has_many :order_items
belongs_to :merchant
has_and_belongs_to_many :categories
validates :name, presence: true, uniqueness: true
# by default numericality doesn't allow value of nil
validates :price, numericality: { only_integer: true, greater_than: 0... |
class ChangeBackDuration < ActiveRecord::Migration[5.2]
def change
change_column :services, :duration, :time
end
end
|
module Fullcalendar
module Generators
class InstallGenerator < ::Rails::Generators::Base
source_root File.expand_path("../templates", __FILE__)
desc "This generator enables you to use Fullcalendar Jquery in your rails app and adds the required lines to application.js and .css in app/ass... |
require './lib/tic_tac_toe/logic.rb'
describe Game do
let(:game) { Game.new }
before do
# game
game.add_player(1, 'Darshan') # X
game.add_player(2, 'Fabien') # O
end
it 'returns game players' do
expect(game.players[1].name).to eql('Darshan')
expect(game.players[2].name).to eql('Fabien')
... |
require 'model_spec_helper'
describe Task do
it { should validate_presence_of(:action) }
it { should validate_presence_of(:time_expression) }
it { should validate_presence_of(:user_id) }
context "using repository" do
let(:attributes) { build_attributes_for(:task) }
class TimeZoneConverter
def s... |
module CustomHelpers
def page_title
[current_page.data.title, config[:site_name]].reject(&:blank?).join(' | ')
end
def active_nav(page)
'class="active"' if current_page?(page)
end
def current_page?(page)
if page == 'home'
current_page.path == 'index.html'
else
current_page.path.include? ... |
module Refinery
module NewsSections
class Engine < Rails::Engine
extend Refinery::Engine
isolate_namespace Refinery::NewsSections
engine_name :refinery_news_sections
before_inclusion do
Refinery::Plugin.register do |plugin|
plugin.name = "news_sections"
plugin... |
require "rails"
module Thincloud
module Test
module Rails
class Railtie < ::Rails::Railtie
initializer "thincloud.test.rails.generators" do |app|
app.config.generators do |g|
g.test_framework :mini_test, spec: true, fixture: false
end
end
end
end
... |
require 'active_support/core_ext'
require 'icalendar'
module Timetable
class Cache
COLLECTION = "cache"
# Return whether a particular course ID is cached in the database.
# A course ID is considered cached if there is a corresponding record
# in the database and that record is no more than 30 minute... |
require File.dirname(__FILE__) + '/../test_helper'
class ForumPostTest < Test::Unit::TestCase
fixtures :users, :forums, :forum_posts
def test_create_post_and_reply
pst = ForumPost.new( :user_id => users(:quentin),
:subject => 'Subject',
:body => 'Body body, wanna ....',
:forum_id => 1)
... |
module LogHelper
def error(message)
log "[#{self.class}::ERROR] #{message}\n"
end
def warn(message)
log "[#{self.class}::WARNING] #{message}\n"
end
def info(message)
log "[#{self.class}::INFO] #{message}\n"
end
def debug(message)
log "[#{self.class}::DEBUG] #{message}\n"
end
priva... |
['ant', 'bear', 'cat'].each_with_object({}) do |value, hash|
hash[value[0]] = value
end
# {"a": "ant", "b": "bear", "c": "cat"} |
class Customer < ApplicationRecord
has_many :orders, dependent: :destroy
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/
def self.search_cus(search_cus)
where('na... |
require 'rails_helper'
RSpec.describe Guide::NodeView do
let(:view) do
described_class.new(node: structure,
diplomat: diplomat,
bouncer: bouncer,
node_path: node_path)
end
let(:structure) do
instance_double(Guide::Structure,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.