text stringlengths 10 2.61M |
|---|
#!/usr/bin/env ruby
require 'optparse'
require 'json'
required_options = {
input: nil,
output: nil
}
OptionParser.new do |parser|
parser.on("-i", "--input PATH", "A path to the input file.") do |v|
required_options[:input] = v
end
parser.on("-o", "--output PATH", "A path to the output file.") do |v|
... |
# Reversed Arrays (Part 2)
# https://launchschool.com/exercises/577016f3
# Write a method that takes an Array, and returns a new Array with the elements of the original list in reverse order. Do not modify the original list.
#You may not use Array#reverse or Array#reverse!, nor may you use the method you wrote in the... |
require 'spec_helper'
describe Genre do
before do
Genre.delete_all
end
it 'has a valid factory' do
create(:genre).should be_valid
end
it 'is invalid without a name' do
build(:invalid_name_genre).should_not be_valid
end
end |
class Exercise < ApplicationRecord
has_and_belongs_to_many :collections
CATEGORIES = ["Chest", "Legs", "Back", "Arms", "Core"]
validates :category, presence: true, inclusion: {in: CATEGORIES}
validates :name, presence: true, uniqueness: true
end
|
class FTMGATE
class FTM
attr_accessor :gid, :control, :input1, :input2, :output1, :output2
def initialize(gid, control, input1, input2)
@gid = gid
@control = control
@input1 = input1
@input2 = input2
@output1 = check(@input1)
@output2 = check(@input2)
end
def in... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :employees
# get '/employee' , to: "employees#index"
root "employees#index"
get 'employees/new' , to: "employees#new"
#how to make a url prefix
# get 'employees/ed... |
# frozen_string_literal: true
RSpec.describe Api::V1::ChangePassword::CreateAction do
let(:action) { described_class.new }
describe '#call' do
subject(:call) do
action.call(input)
end
let!(:user) { create(:user, :reset_password_requested) }
let(:input) do
jsonapi_params(
attri... |
require 'puppet/util/windows'
require 'pathname'
begin
require File.expand_path('../../../util/ini_file', __FILE__)
rescue LoadError
# in case we're not in libdir
#require File.expand_path('../../../../../spec/fixtures/modules/inifile/lib/puppet/util/ini_file', __FILE__)
end
Puppet::Type.type(:so_systemaccess)... |
class Test::Unit::TestCase
def self.should_render_partial(partial)
should "render partial #{partial.inspect}" do
assert_template :partial => partial.to_s
end
end
end
|
module Serializable
extend ActiveSupport::Concern
def serialize_customer(customer)
Api::V1::CustomerSerializer.new(customer)
end
def serialize_agent(agent)
Api::V1::AgentSerializer.new(agent)
end
def serialize_property(property)
Api::V1::PropertySerializer.new(property)
end
def serialize... |
class MainNavigationCell < Cell::Rails
helper :cms
# Cell actions:
cache(:show, if: :really_cache?) do |cell, page|
[
RailsConnector::Workspace.current.revision_id,
page && page.homepage.id,
]
end
def show(page)
@page = page
@root = page.homepage
if @root
render
e... |
require 'json'
def handler(event:, context:)
qs = event.fetch("queryStringParameters", {})
name = qs.fetch("name", "unknown user")
STDERR.puts "Handling ALB request for #{name}"
{
"statusCode": 200,
"statusDescription": "200 OK",
"isBase64Encoded": false,
"headers"... |
require 'rails_helper'
RSpec.describe Zone, type: :model do
it { should have_valid(:name).when('Neighborhood', 'Spot') }
it { should_not have_valid(:name).when(nil, '') }
end
|
#!/usr/bin/env ruby
require 'optparse'
root_path = File.expand_path(File.join(File.dirname(__FILE__), '..'))
runner_path = File.join(root_path, 'lib', 'hypgen.rb')
config_path = 'config.yml'
OptionParser.new do |opts|
opts.banner = "Usage: hypgen-worker [options]"
opts.on("-c", "--configuration PATH", "Yaml wor... |
class IndexController < ApplicationController
def index
if logged_in?
redirect_to :controller => "visit", :action => "index"
end
end
end |
# frozen_string_literal: true
require 'test_helper'
module Resque
module Failure
class EmailNotificationTest < ActiveSupport::TestCase
setup do
@notification = Resque::Failure::EmailNotification.new(
sample_exception, 'worker', 'queue', 'payload'
)
end
def test_save
... |
# require './lib/transaction.rb'
# require './lib/bankaccount.rb'
#
#
#
# describe Transaction do
#
# it "includes the date when created" do
# my_account = BankAccount.new(2000)
# new_transaction = Transaction.new
# expect(new_transaction).to eq(nil)
# end
#
# it "shows the credit on balance after adding... |
#!/usr/bin/env ruby
require 'rubygems'
require 'redis'
require 'ostruct'
require 'optparse'
DEFAULTS = {
:sample_size => 10_000,
:host => IO.popen("ifconfig | grep -o -P \"(192|127)\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\" | head -n 1").read.strip
}
$defaults = DEFAULTS
$options = {}
OptionParser.new do |opts|
... |
# 08 - Multiline Comment
=begin
Multiline
Comment
=end |
#Object-oriented programming is a programming paradigm that privileges objects rather than actions and data rather than functions or logic.
#The most popular object-oriented languages, such as Java, Perl, Python, Ruby, Objective-C, Smalltalk and Swift are class-based. .
#Objects are instances of classes, which usuall... |
# Represents a file which stored on some cloud server
class CloudFile < ActiveRecord::Base
belongs_to :library, inverse_of: :files
belongs_to :folder, inverse_of: :files
end
|
module Gradebook
module Reports
class Builder
attr_accessor :report, :template, :component
def self.build_report (report)
builder = Builder.new(report)
builder.build
end
def initialize (report)
@report = report
@template = report.report_template
@c... |
require "application_system_test_case"
# to create this file, run following command
# rails generate system_test games
# to run the test
# rails test:system
# you need chromedriver
# following command can install chromedriver
# brew cask install chromedriver
class GamesTest < ApplicationSystemTestCas... |
class RemoveSorceryFieldsFromUsers < ActiveRecord::Migration
def change
remove_column :users, :crypted_password
remove_column :users, :salt
remove_column :users, :remember_me_token
remove_column :users, :remember_me_token_expires_at
remove_column :users, :reset_password_token
remove_column :us... |
class Branch < ActiveRecord::Base
# relationships
belongs_to :branch_group
has_many :delivery_zones,
foreign_key: "branch_id",
class_name: "BranchDeliveryZone"
accepts_nested_attributes_for :delivery_zones
has_many :employees
has_many :users, -> { where(role: :employee) },
... |
module Binders
class Users < Bowline::Binders::Base
bind User
class << self
def admins
self.items = User.admins.all
end
end
def update(attrs)
if @item.update_attributes(attrs)
page.flash("Successfully updated").call
else
page.flash_error("Errors ... |
#
# Trusterd - HTTP/2 Web Server scripting with mruby
#
# Copyright (c) MATSUMOTO, Ryosuke 2014 -
#
# 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 li... |
require 'test_helper'
class VotesControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
test "should add a row" do
test_candidate = Candidate.create!(name: "first tester", hometown: "home", district: "13", party: "indep")
test_voter = Voter... |
class Intersections < ActiveRecord::Migration
def change
create_table :intersections do |t|
t.string :street1, null: false, index: true
t.string :street2, null: false, index: true
end
end
end
|
require 'find'
class Capture < ActiveRecord::Base
has_many :user_assets
belongs_to :user
def acquire_contents
if File.directory? self.path
sub_paths = Find.find(self.path)
.reject {|path| File.directory? path }
sub_paths.each do |sub_path|
create_asset(file_nam... |
require 'rails_helper'
RSpec.describe DevicesController, type: :controller do
let(:customer) { create(:customer) }
let(:existing_device) { create(:device, customer_id: customer.id) }
let(:new_device) { double(:device) }
describe "GET new" do
login_user
before do
allow(Device).to receiv... |
# frozen_string_literal: true
module WasteExemptionsShared
class Exemption < ActiveRecord::Base
self.table_name = "exemptions"
has_many :enrollment_exemptions, dependent: :restrict_with_exception
accepts_nested_attributes_for :enrollment_exemptions
has_many :enrollments,
class_name: "E... |
# Given an array of questions like this:
# questions = ["What is your name", "How are you?", "Is that right?",
# "Are you John?", "How is everything?"]
# and returns an array of questions whose total character count is greater than 15.
# Bonus: Do it in two ways, one of them using select method for Ruby Arrays.
def ... |
FactoryBot.define do
factory :like do
association :topic, strategy: :build
association :user, strategy: :build
end
end
|
# frozen_string_literal: true
module FlashableConcern
extend ActiveSupport::Concern
def flash_action(status: flash_status)
{ message: message, status: status }
end
private
def flash_status
response.successful? ? :success : :negative
end
def model_name
controller_name.classify.constantize.... |
# frozen_string_literal: true
module AchievementHelper
def achievement_unlocked(user_id, name)
ach = Achievement.find_by_name(name)
return unless ach.present?
return if UserAchievement.find_by_user_id_and_achievement_id(user_id, ach.id).present?
UserAchievement.create!(user_id: user_id, achievement_... |
module GameConstants
VALUES = %w(rock paper scissors lizard spock).freeze
WINNING_COMBOS = {
'rock' => %w(scissors lizard),
'paper' => %w(rock spock),
'scissors' => %w(paper lizard),
'lizard' => %w(paper spock),
'spock' => %w(scissors rock)
}.freeze
SHORTENED_VALID_CHOICES = {
... |
class CreateSettings < ActiveRecord::Migration
def change
create_table :settings do |t|
t.string :slug
t.string :config_key
t.string :config_value
t.boolean :destroyable, default: true
t.boolean :editable, default: true
t.timestamps null: false
end
end
end
|
module CDI
module V1
class SimpleGameQuestionAnswerSerializer < ActiveModel::Serializer
root false
attributes :id, :game_question_id, :user_id, :answer_body, :option_id, :correct?,
:created_at, :updated_at, :corrected_at
def filter(keys)
blacklist_keys = object.optio... |
# == Schema Information
#
# Table name: reporter_images
#
# id :bigint(8) not null, primary key
# user_id :bigint(8)
# title :string
# caption :string
# source :string
# reporter_image :string
# created_at :datetime not null
# updated_at :datetim... |
class TicketType < ActiveRecord::Base
belongs_to :event
has_many :tickets
validates :max_quantity, presence: true
def remaining_ticket
tickets = self.tickets
count = 0
tickets.each do |t|
count += t.count
end
max_quantity - count
end
end
|
require_relative '../spec_helper'
describe 'custom_resource_test::default' do
context 'When all attributes are default, on an unspecified platform' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new do |node, _server|
node.set['aws-kms']['aws_access_key_id'] = 'test'
node.set['aws-kms... |
class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
has_many :messages, foreign_key: "from"
has_many :received_messages, foreign_key: "to", class_name: "Messag... |
require "rails_helper"
RSpec.describe ContestantScore do
subject { build(:contestant_score) }
it "has a valid factory" do
expect(subject.valid?).to eq true
subject.save!
end
describe "validations" do
it { is_expected.to validate_presence_of :contestant }
it { is_expected.to validate_presence_... |
=begin
FactoryGirl.define do
factory :user do
name "Michael Hartl"
email "michael@example.com"
password "foobar"
password_confirmation "foobar"
end
end
=end
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com" }
password "foobar"... |
class ApplicationController < ActionController::Base
helper_method :get_slack_access_token
def get_slack_access_token(code, client_id, client_secret, redirect_uri)
response = HTTParty.get("https://slack.com/api/oauth.access?code=#{code}&client_id=#{client_id}&client_secret=#{client_secret}&redirect_uri=#{redir... |
# == Schema Information
#
# Table name: fixtures
#
# id :integer not null, primary key
# name :string not null
# slug :string not null
# track_id :integer not null
# start_time :datetime not null
# short_desc :text
# long_desc :text
# created_... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
def check_authorized
unless session[:user_id]
respond_to do |format|
format.json { render json: {}, status: 422 }
end
end
end
end
|
class PostsController < ApplicationController
before_action :check_author, only: [:edit, :update]
def check_author
@post = current_user.posts.find(params[:id])
render json: "Not Allowed", status: 422 unless @post
end
def new
@post = Post.new
render :new
end
... |
# Copyright (C) 2014 Jan Rusnacko
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of the
# MIT license.
require 'spec_helper'
describe Xenuti::ReportSender do
let(:config) do
c = {
'report' => {
'send_... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
before_action :authenticate, except: %i[signup signin new create]
def current_user
@_current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id])
end
private
... |
# frozen_string_literal: true
#
# Fluentd Kubernetes Metadata Filter Plugin - Enrich Fluentd events with
# Kubernetes metadata
#
# Copyright 2017 Red Hat, 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 ... |
class Drug < ApplicationRecord
has_many :drug_generics
has_many :generics, through: :drug_generics
has_many :drug_categories
has_many :categories, through: :drug_categories
has_many :rx_drugs
has_many :rxs, through: :rx_drugs
has_many :likes
belongs_to :company
belongs_to :country
belongs_to :f... |
# frozen_string_literal: true
module Api
module V1
class Container
extend Dry::Container::Mixin
namespace 'params' do
register 'validate' do
Params::Validate.new
end
register 'deserialize' do
Params::Deserialize.new
end
register 'deserial... |
class Cat
attr_accessor :name, :color
def initialize(name, color)
@name = name; @color = color
end
def add
puts "#{self.name}-#{self.color}"
end
end
cat=Cat.new("Tama", "white")
cat.add |
#variables de clase @@
#variables de instancia @
#ueden ser usasdas desde metodos de la clase como metodos del objeto
#usar variables de instancia cuando no queremos que las variables se hereden a las clases hijas
class Video
@@de_clase="Clasee" #las hijas si pueden acceder e inclusive sustituir su valor
... |
Then /^I should see an application with name "([^\"]*)"$/ do |name|
app = App.find_by_name(name)
response.should have_tag("##{app.identifier}")
end
|
module NavigationHelpers
module Refinery
module Elements
def path_to(page_name)
case page_name
when /the list of documents/
admin_elements_documents_path
when /the new document form/
new_admin_elements_document_path
when /the document titled "?([^\"]*)"?/
... |
class BoardsController < ApplicationController
load_and_authorize_resource :user
load_resource :board, :through => :user, :shallow => true
authorize_resource :board, :through => :user, :shallow => true
before_action :assign_owner, :only => [:create]
before_action :handle_issues_attributes, :only => [:upda... |
# spec/controllers/activity_feed_controller_spec.rb
require 'spec_helper'
describe ActivityFeedController, :type => :controller do
before (:each) do
@lookup = FactoryGirl.create(:lookup)
@user = FactoryGirl.create(:user)
@activity_feed = FactoryGirl.create(:activity_feed)
end
describe "GET 'show'" do... |
require_relative "board"
require_relative "player"
require_relative "computerplayer"
class BattleshipGame
attr_accessor :player, :board, :userboard, :computer
def initialize(player = HumanPlayer.new, board = Board.new)
@player = player
@board = board
@userboard = Board.new
@computer = ComputerPla... |
class CreateElements < ActiveRecord::Migration
def change
create_table :elements do |t|
t.string :name
t.string :version
t.float :standard_deviation
t.float :mean
t.float :weight_extraversion
t.float :weight_conscientiousness
t.float :weight_neuroticism
t.float :wei... |
class BrigadeProjectsUser < ActiveRecord::Base
belongs_to :brigade_project
belongs_to :user
end
|
class AddPhotourlToDidGoods < ActiveRecord::Migration[5.2]
def change
add_column :did_goods, :photourl, :string, default: "https://cdn.diariodolitoral.com.br/upload/dn_noticia/2019/01/bolsonaro-fp134.jpg"
end
end
|
def find(id)
@candidates.detect {|person| person[:id] == id ? person : nil}
end
def experienced?(candidate)
yes_to_exp = candidate[:years_of_experience] >= 2
return "Candidate has the requested years of experience: #{yes_to_exp}"
end
def has_enough_github_pts?(candidate)
candidate[:github_... |
class DevicesController < ApplicationController
before_action :set_device, only: [:show, :edit, :update, :destroy]
layout "lifts"
# GET /devices
# GET /devices.json
def index
if params[:search].present?
verify_date = Date.parse params[:search]
@devices = Device.expired( verify_date )
else
@devic... |
class AddTimeTakenToBmis < ActiveRecord::Migration
def change
add_column :bmis, :time_taken, :time
end
end
|
# Copyright (c) 2009-2011 VMware, Inc.
require 'postgresql_service/pg_timeout'
module VCAP
module Services
module Postgresql
end
end
end
# Give various helper functions on version differences
module VCAP::Services::Postgresql::Version
def pg_version(conn, opts={})
# by default, will return major.m... |
class Trie
attr_accessor :map_of_children, :end_of_word
def initialize()
@map_of_children = {}
@end_of_word = false
end
# Inserts a word into the trie.
# :type word: String
# :rtype: Void
def insert(word)
trie_ptr = self
word.each_char.with_index do |ch, i... |
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'bolt'
require 'bolt/catalog'
require 'json'
# This accepts a catalog request on stdin:
# { "code_ast": "JSON serialized Puppet AST",
# "code_string": "String of code, ignored if AST is provided",
# "modulepath": "Array of directories to use as the modulep... |
require 'test_helper'
require 'product_controller'
require 'product'
describe ProductController do
it "cannot be accessed more than once" do
-> { ProductController.new }.must_raise NoMethodError
end
it "retrieves a product" do
PRODUCT = Product.new "Tomato", :fruit
controller = ProductController.ins... |
load '../Scripts/podfile-helpers.rb'
puts "---> value of local_build=#{is_local_build}"
setup_flipper = should_add_flipper_on_local_build
puts "---> value of setup_flipper=#{setup_flipper}"
remove_app_extensions = should_remove_app_extensions_on_local_build
puts "---> value of remove_app_extensions=#{remove_app_exte... |
# frozen_string_literal: true
module Tikkie
module Notifications
# Refund notification.
class RefundNotification
NOTIFICATION_TYPE = 'REFUND'
attr_reader :body
def initialize(body)
@body = body
end
def subscription_id
body[:subscriptionId]
end
def... |
module Sshez
class Exec
def process(args)
# parse the params to get the options
if args.length == 0
args[0] = '-h'
elsif args[0] == 'list'
return ConfigFile.list
elsif args[0] == 'remove'
if args[1]
return ConfigFile.remove(args[1])
else
... |
require "commission_junction_stats/version"
require 'net/https'
require 'uri'
require 'nokogiri'
class CommissionJunctionStats
attr_reader :total_revenue, :total_revenue_by_advertiser
# Your code goes here...
def initialize (authorization_token, start_date, end_date)
@total_revenue = 0
@total_reve... |
require File.dirname(__FILE__) + '/../../test_helper'
class SlaveTest < ActiveSupport::TestCase
def setup
@project = Project.create(:name => 'some_project')
@plan = @project.plans.create(:name => 'some_plan')
end
test "should find running builds" do
slave = Slave.create(:name => 'localhost', :prot... |
class Movie < ActiveRecord::Base
#==shcema info
#create_table "movies", force: :cascade do |t|
# t.integer "article_id", limit: 4, null: false
# t.integer "youtube_id", limit: 4, default: 0, null: false
# t.datetime "created_at", null: false
# t.datetime "updated_a... |
require 'spec_helper'
describe ThumbnailHelper do
describe 'thumbnail_tag' do
let(:work) { GenericWork.new }
let(:document) { SolrDocument.new work.to_solr }
context "when the representative is set" do
let(:path) { "ksl:test123" }
before do
allow(document).to receive(:representati... |
# frozen_string_literal: true
module Ayte
module Chef
module Cookbook
module ElasticSearch
class Response
attr_accessor :code
attr_accessor :body
attr_accessor :headers
attr_accessor :request
def errors?
body&.fetch('errors', false)
... |
FactoryGirl.define do
factory :project do
sequence(:name) {|n| "epic undertaking #{n}" }
description "I am a description of this project."
fellow
end
factory :person do
first_name "Bruce"
sequence(:last_name){|n| "Wayne #{n}"}
sequence(:uid) {|s| "123#{s}" }
admin false
tag_list ... |
module Common
class RemoveOnesignalNotification
prepend SimpleCommand
def initialize(current_user, args = {})
@user = current_user
@args = args
end
def call
uri = URI.parse("https://onesignal.com/api/v1/notifications/#{@args[:one_signal_id]}?app_id=#{ENV['ONE_SIGNAL_APP_ID']}")
... |
require 'player'
describe Player do
subject(:player) { described_class.new('Ed') }
let(:player2) { double :player2, receive_damage: nil }
it 'returns its own name' do
expect(player.name).to eq 'Ed'
end
it 'returns its hit points' do
expect(player.hp).to eq 100
end
describe '#receive_damage' do... |
describe 'status', type: :request do
it 'responds with :ok' do
get '/'
expect(response).to have_http_status(:ok)
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "precise32"
config.vm.box_url = "http://files.vagrantup.com/precise32.box"
config.vm.network :forwarded_port, guest: 80, host: 8000
# config.vm.network :private_network, ip: "192.168.33.10"
config.vm.network :public_... |
require 'tomdoc'
require 'shomen/metadata'
require 'shomen/model' # TODO: have metadata in model
module TomDoc
module Generators
# Shomen generator for TomDoc.
#
# IMPORTANT: Unfortunately TomDoc's parser does not yet provide enough
# information to generate a substantial Shomen model. As things c... |
json.array! @addresses do |da|
json.id da.address.id
json.label da.label
json.url api_v1_delivery_address_url(da, format: :json)
end
|
class Episode < ApplicationRecord
belongs_to :member
has_many :comments
has_attached_file :episode_thumbnail, styles: { large: "1000x1000#", medium: "500x500#" }
validates_attachment_content_type :episode_thumbnail, content_type: /\Aimage\/.*\z/
has_attached_file :mp3
validates_attachment :mp3, :content_t... |
# 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... |
# coding: utf-8
require 'spec_helper'
describe WorkersController do
let(:organization) { FactoryGirl.create(:organization_with_services) }
let(:worker) { FactoryGirl.create(:worker_with_services, organization_id: organization.id) }
before(:each) do
@request.host = "#{organization.domain}.com"
@photo = f... |
class School < ActiveRecord::Base
has_many :courses, dependent: :destroy
validates :name, presence: true, length: { maximum: 255 }
validates :country, presence: true, length: { maximum: 255 }
validates :website, presence: true, length: { maximum: 255 }
validates :primary_colour, presence: true, length: { ma... |
class Platform < ApplicationRecord
belongs_to :subscription, foreign_key: 'subscription_id'
def self.search(value)
if value
where('product LIKE ?', "%#{value}%")
else
where(nil)
end
end
end
|
require 'whitehall/document_filter/options'
require 'cgi'
class EmailSignup
class FeedUrlValidator
attr_reader :feed_url, :feed_type, :feed_object_slug, :filter_options_describer
def initialize(feed_url)
@feed_url = feed_url
@filter_options_describer = Whitehall::DocumentFilter::Options.new
... |
class SetCouponToNilInOrders < ActiveRecord::Migration
def up
Order.where(coupon_id: 0).update_all("coupon_id = NULL")
end
def down
end
end
|
require 'sinatra'
require 'json'
require 'net/http'
require 'sinatra/base'
require 'active_support/core_ext/hash'
require 'nokogiri'
require 'csv'
require 'geocoder'
require 'FlightXML2RESTDriver'
class EVAServer < Sinatra::Base
def self.parse_sst_csv()
arr = Array.new
CSV.foreach("time_series_from_netcdf.csv") d... |
class User < ActiveRecord::Base
has_many :orders
has_many :addresses
end
|
require_relative '../feature_helper'
feature 'Only author can edit questions', %q(
In order to rephrase question
As an author
I should be able to edit my question
) do
given(:user) { create(:user) }
given(:author) { create(:user) }
given(:question) { create(:question, user: author) }
scenario 'Unauthenticated... |
class Restaurant
attr_reader :opening_time, :name, :dishes
def initialize(opening_time, name)
@opening_time = opening_time
@name = name
@dishes = []
end
def closing_time(open_hours)
hours = (@opening_time.to_i + open_hours)
"#{hours}:00"
end
def add_dish(dish)
@dishes << dish
end... |
class Invite < ActiveRecord::Base
attr_accessor :prev_invite
## Relations
belongs_to :user
belongs_to :invitee, class_name: 'User', foreign_key: 'invitee_id'
## Validations
validates :user, presence: true
validates :email, format: { with: /\A(^.+@.+$)\z/i }
validate :check_invitee_exists, :check_last... |
class MessagesController < ApplicationController
def create
@message = Message.new (message_params)
if @message.save
puts "message saved!"
flash.notice = "Thank you for your message!"
#This is where the mailer stuff goes
# ContactMailer.with(@message).contact_email.deliver_now... |
class User < ActiveRecord::Base
validates_presence_of :name, :email, :username
validates :name, format: { with: /\A[[:alpha:]\s]+\z/,
message: 'debe contener caracteres válidos' }
validates :email, uniqueness: true, email: true
validates :username, uniqueness: true,
format: { with: /\A[[:alpha:]\d\_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.