Paginating DataMapper - sinatra

I have a pretty basic model called Review (basically just an ID serial and some text columns) and I'm making a simple pagination system for it.
The following code:
Review.all(:limit => per_page, :offset => offset, :order => [ :id.asc ])
Returns the correct objects if the offset is 0, but is problematic if offset is anything else.
With an offset > 0, the code:
reviews = Review.all(:offset => offset, :limit => per_page);
p reviews
p reviews.count
returns
[#<Review #id=11 #created_at=<not loaded> #rating=<not loaded> #title=<not loaded> #text= <not loaded> #name=<not loaded> #from=<not loaded> #stay_date=<not loaded> #helpful=0 #not_helpful=0 #response=<not loaded>>, #<Review #id=12 #created_at=<not loaded> #rating=<not loaded> #title=<not loaded> #text=<not loaded> #name=<not loaded> #from=<not loaded> #stay_date=<not loaded> #helpful=0 #not_helpful=0 #response=<not loaded>>, #<Review #id=13 #created_at=<not loaded> #rating=<not loaded> #title=<not loaded> #text=<not loaded> #name=<not loaded> #from=<not loaded> #stay_date=<not loaded> #helpful=0 #not_helpful=0 #response=<not loaded>>, #<Review #id=14 #created_at=<not loaded> #rating=<not loaded> #title=<not loaded> #text=<not loaded> #name=<not loaded> #from=<not loaded> #stay_date=<not loaded> #helpful=0 #not_helpful=0 #response=<not loaded>>, #<Review #id=15 #created_at=<not loaded> #rating=<not loaded> #title=<not loaded> #text=<not loaded> #name=<not loaded> #from=<not loaded> #stay_date=<not loaded> #helpful=0 #not_helpful=0 #response=<not loaded>>]
0
How is this? It's finding the objects, but can't count them?

You could convert the lazy list into an array with #to_a and #count that (e.g., Review.all(:limit => 10, :offset => 10).to_a.count).
By the way, there is rather nice syntactic sugar for limit and offset in the spirit of Array: Review[offset,limit].
Complete example:
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
require 'dm-sweatshop' # just to load some fixtures
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, "sqlite::memory:")
class Review
include DataMapper::Resource
property :id, Serial
property :title, String, :required => true
property :rating, Integer, :min => 1, :max => 10
property :created_at, DateTime, :default => lambda {Time.now}
end
DataMapper.finalize.auto_migrate!
class FixtureHelpers # Just to cache for sweatshop, avoid polluting top-level
##date_range = (Date.new(2003)..Date.today).to_a
def self.rand_date; ##date_range.choice end
end
Review.fix {{
:title => /\w+/.gen.capitalize,
:rating => (1..10).to_a.choice,
:created_at => FixtureHelpers.rand_date
}}
100.of {Review.gen}
p Review[95,10].to_a.count
# ~ (0.000105) SELECT "id", "title", "rating", "created_at" FROM "reviews" ORDER BY "id" LIMIT 10 OFFSET 95
# => 5

Related

Calling Document.find with nil is invalid in mongodb

I am using mongodb with active merchant gem in rails4. While use rails cast tutorial #145 Integrating Active Merchant.
Error
Problem: Calling Document.find with nil is invalid. Summary: Document.find expects the parameters to be 1 or more ids, and will return a single document if 1 id is provided, otherwise an array of documents if multiple ids are provided. Resolution: Most likely this is caused by passing parameters directly through to the find, and the parameter either is not present or the key from which it is accessed is incorrect.
Order Controller
class OrderController < ApplicationController
include ActiveMerchant::Billing::Integrations
def new
#cart = current_cart
#order = Order.new
end
def success
end
def failure
end
def create
#order = current_cart.build_order(params_order)
#order.ip_address = request.remote_ip
if #order.save
if #order.purchase
render :action => "success"
else
render :action => "failure"
end
else
render :action => 'new'
end
end
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
def params_order
params.require(:order).permit(:first_name, :last_name, :card_type, :card_number, :card_verification, :card_expires_on)
end
end
Model
order.rb
class Order < ActiveRecord::Base
belongs_to :cart
has_many :transactions, :class_name => "OrderTransaction"
attr_accessor :card_number, :card_verification
#validate_on_create :validate_card
def purchase
response = GATEWAY.purchase(price_in_cents, credit_card, purchase_options)
transactions.create!(:action => "purchase", :amount => price_in_cents, :response => response)
cart.update_attribute(:purchased_at, Time.now) if response.success?
response.success?
end
def price_in_cents
return 100 #(cart.total_price*100).round
end
private
def purchase_options
{
:ip => ip_address,
:billing_address => {
:name => "Ryan Bates",
:address1 => "123 Main St.",
:city => "New York",
:state => "NY",
:country => "US",
:zip => "10001"
}
}
end
def validate_card
unless credit_card.valid?
credit_card.errors.full_messages.each do |message|
errors.add_to_base message
end
end
end
def credit_card
#credit_card ||= ActiveMerchant::Billing::CreditCard.new(
:type => card_type,
:number => card_number,
:verification_value => card_verification,
:month => card_expires_on.month,
:year => card_expires_on.year,
:first_name => first_name,
:last_name => last_name
)
end
end
order_transaction.rb
class OrderTransaction
include Mongoid::Document
field :order_id, type: Integer
field :action, type: String
field :amount, type: Integer
field :success, type: Mongoid::Boolean
field :authorization, type: String
field :message, type: String
field :params, type: String
end
cart.rb
class Cart
include Mongoid::Document
has_one :order
end
Route.rb File
get "order/new"
get "order/success"
get "order/failure"
post "order/create", :to => "order#create", as: :orders
resources :cart do
resource :order
end
View
new.html.haml
%br
%br
%h5.text-center
= " Order "
=form_for :order, url:{action: "create"}, html:{class: "form-horizontal"} do |f|
%div.form-group
=f.label :first_name, 'First Name' , {:class => 'col-lg-2 control-label'}
%div.col-lg-3
=f.text_field :first_name, {:class => 'form-control', :placeholder => "First Name"}
%div.form-group
=f.label :last_name, 'Last Name', {:class => 'col-lg-2 control-label'}
%div.col-lg-3
=f.text_field :last_name, {:class => 'form-control', :placeholder => "Last Name"}
%div.form-group
=f.label :card_type, 'Card Type', {:class => 'col-lg-2 control-label'}
%div.col-lg-3
=f.select(:card_type, [["Visa", "visa"], ["MasterCard", "master"], ["Discover", "discover"], ["American Express", "american_express"]], {}, {:class => 'form-control', :placeholder => ""})
%div.form-group
=f.label :card_number, 'Card Number', {:class => 'col-lg-2 control-label'}
%div.col-lg-3
=f.text_field :card_number, {:class => 'form-control', :placeholder => "378282246310005"}
%div.form-group
=f.label :card_verification, 'Card Verification', {:class => 'col-lg-2 control-label'}
%div.col-lg-3
=f.text_field :card_verification, {:class => 'form-control', :placeholder => "YES"}
%div.form-group
=f.label :card_expires_on, 'Card Expire Date', {:class => 'col-lg-2 control-label'}
%div.col-lg-3
=f.date_select :card_expires_on, :discard_day => true, :start_year => Date.today.year, :end_year => (Date.today.year+10), :add_month_numbers => true
%div.form-group
%div.col-lg-offset-2.col-lg-10
=f.submit :class => 'btn btn-primary'
Error Occur
Mongoid::Errors::InvalidFind in OrderController#new
Problem: Calling Document.find with nil is invalid. Summary: Document.find expects the parameters to be 1 or more ids, and will return a single document if 1 id is provided, otherwise an array of documents if multiple ids are provided. Resolution: Most likely this is caused by passing parameters directly through to the find, and the parameter either is not present or the key from which it is accessed is incorrect.
** Your suggestion will helpful. Thanks in advanced**
OrderController#new calls OrderController#current_cart which runs Cart.find(session[:cart_id]). There's no :cart_id at session start, i.e., session[:cart_id] is nil, and you get the Mongoid::Errors::InvalidFind exception above. Note that your rescue clause will not rescue that exception as you are rescuing ActiveRecord::RecordNotFound. You are using Mongoid, not ActiveRecord, and must program accordingly. Best wishes.

Typo3 6.0.2 Add RTE Class

how can i add new classes to TYPO3 RTE (version 6.0.2)
i tried the same way as with Typo3 4 :
- created a css file in fileadmin folder (fileadmin/css/rte.css)
- add style in this css file
- add those lines in page TSConfig :
RTE.default {
classesParagraph >
classesTable >
classesTD >
classesLinks >
classesCharacter >
classesAnchor >
classesImage >
ignoreMainStyleOverride=1
showTagFreeClasses=1
contentCSS = /fileadmin/css/rte.css
showButtons = *
showTagFreeClasses = 1
proc.allowedClasses >
}
RTE.classes {
left.name=Float left
}
but nothing change, my added classes won't show in RTE...
thanks in advance.
I think some configuration options have changed in newer versions of TYPO3.
Deprecated property => Use instead
disableRightClick => contextMenu.disable
disableContextMenu => contextMenu.disable
hidePStyleItems => buttons.formatblock.removeItems
hideFontFaces => buttons.fontstyle.removeItems
fontFace => buttons.fontstyle.addItems
hideFontSizes => buttons.fontsize.removeItems
fontSize => buttons.fontsize.addItems
classesCharacter => buttons.textstyle.tags.span.allowedClasses
classesParagraph => buttons.blockstyle.tags.div.allowedClasses
classesTable => buttons.blockstyle.tags.table.allowedClasses
classesTD => buttons.blockstyle.tags.td.allowedClasses
classesImage => buttons.image.properties.class.allowedClasses
classesLinks => buttons.link.properties.class.allowedClasses
blindImageOptions => buttons.image.options.removeItems
blindLinkOptions => buttons.link.options.removeItems
defaultLinkTarget => buttons.link.properties.target.default
RTE.default.classesAnchor => RTE.default.buttons.link.properties.class.allowedClasses
RTE.default.classesAnchor.default.[link-type] => RTE.default.buttons.link.[link-type].properties.class.default
mainStyleOverride => contentCSS
mainStyleOverride_add.[key] => contentCSS
mainStyle_font => contentCSS
mainStyle_size => contentCSS
mainStyle_color => contentCSS
mainStyle_bgcolor => contentCSS
inlineStyle.[any-keystring] => contentCSS
ignoreMainStyleOverride => n.a.
disableTYPO3Browsers => buttons.image.TYPO3Browser.disabled and buttons.link.TYPO3Browser.disabled
showTagFreeClasses => buttons.blockstyle.showTagFreeClasses and buttons.textstyle.showTagFreeClasses
disablePCexamples => buttons.blockstyle.disableStyleOnOptionLabel and buttons.textstyle.disableStyleOnOptionLabel
See here: http://forge.typo3.org/issues/28325
In case you still need help: Here is another question with a helpful answer:
Cannot choose text style in RTE
I had the same problem with TYPO3 6.0.2 and many tutorials or forum entries I found contained deprecated properties. With the answer to the aforemetnioned question it worked.
css file rte.css
a.youtube-vintage, a.fb-vintage, a.www-vintage {
color: #9A3811;
}
pagets config
/////////////////////////////////////////////////////////////
// RTE
/////////////////////////////////////////////////////////////
RTE.classes{
youtube-vintage{
name = youtube
value = color:#636466; font-size:15px;
}
fb-vintage{
name = fb
value = color:#9A3811;
}
www-vintage{
name = www
value = color:#9A3811;
}
}
RTE.default{
ignoreMainStyleOverride = 1
useCSS = 1
showTagFreeClasses = 1
contentCSS = fileadmin/templates/css/rte.css
buttons {
blockstyle.tags.div.allowedClasses := addToList(youtube-vintage, fb-vintage, www-vintage)
blockstyle.tags.p.allowedClasses := addToList(youtube-vintage, fb-vintage, www-vintage)
textstyle.tags.span.allowedClasses := addToList(youtube-vintage, fb-vintage, www-vintage)
}
proc.allowedClasses := addToList(youtube-vintage, fb-vintage, www-vintage)
}

Multi dimensional hash sort - Perl [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I really need some help in understanding this hash and processing it with sort.
Here is the hash:
$VAR1 = {
Key1:Key1_si => {
'KeyA' => {
Keya => 'abcd, defg',
keyb => '1000',
keyc => '80%',
keyd => '2011.10.09',
keye => '1234-UR-DDDD',
keyf => 'rwh',
keyg => '600',
keyh => 'red',
keyi => '900',
keyj => '',
keyk =>'int4678_tt',
},
'KeyB' => {
Keya => 'abcd, defg',
keyb => '2000',
keyc => '100%',
keyd => '2011.11.09',
keye => '1234-UR-DDDD',
keyf => 'rwh',
keyg => '500',
keyh => 'red',
keyi => '400',
keyj => '',
keyk =>'int4678_tt',
},
},
};
Question: I want to sort this hash on the basis of 'keyc' whose value is varied. So, I want to sort on the basis like below:
Key1:Key1_si->KeyB->Keyc
Key1:Key1_si->KeyA->keyc
Also, I want to have the output with the sorted values along with the rest of attributes like :
Print:
Key1:Key1_si KeyB Keya keyd Keyc keyf
Key1:Key1_si KeyA keya keyd Keyc keyf
Can somebody please help me with the code in perl to perform sort as mentioned above. I will really appreciate your time and efforts.
You want to sort a list of key pairs, so you have to start by building a list of key pairs. A reference to an array is the obvious answer. Once you've figured this out, everything is straight forward.
Building the list of keys:
my #unsorted_keys;
for my $k1 (keys(%$VAR1)) {
for my $k2 (keys(%{ $VAR1->{$k1} })) {
push #unsorted_keys, [ $k1, $k2 ];
}
}
Sorting those key:
my #sorted_keys = sort {
my ($a_k1, $a_k2) = #$a;
my ($b_k1, $b_k2) = #$b;
( my $a_pc = $VAR1->{$a_k1}{$a_k2}{keyc} ) =~ s/%//;
( my $b_pc = $VAR1->{$b_k1}{$b_k2}{keyc} ) =~ s/%//;
$a_pc <=> $b_pc
} #unsorted_keys;
Iterating over the sorted keys:
for (#sorted_keys) {
my ($k1, $k2) = #$_;
my $hash = $VAR1->{$k1}{$k2};
... do stuff with %$hash ...
}

how to bold a label in zend form element

hi i am using zend form , i want to
bold one of the labels , this is my element's code
$od = new Zend_Form_Element_MultiCheckbox('od');
$od->setLabel(' Add Occupancy Denominations : ');
$od->class = 'od';
$od->addMultiOptions($options['od']);
if (isset($options['od_vals'])) { //value set in edit room type
$od->setValue($options['od_vals']);
}
$od->setDecorators(
array(
array('ViewHelper',
array('helper' => 'formMultiCheckbox')
),
array('Label',
array('class' => 'label')
),
array('HtmlTag',
array('tag' => 'div', 'class' => 'formfield')
),
)
);
i want to bold
Add Occupancy Denominations :
like this
Add Occupancy Denominations :
how can i do this . please help :(
Well, usually, you can gain that effect through the CSS rule.
.zend_form dt label {
font-weight: bold;
}
But that's of course if you keep the default decorators.

Sorting by birthday date my friend list in Facebook API?

I'm creating my own application to show forthcoming friend's birthday. I have a permission to get this dates from facebook and i'm displaying all my friends with their date of birth on my site. My only question is how to display ie. first 10 forthcoming birthdays? i'm using $facebook->api('/me/friends?limit=10) but have not idea how to sort them. Anyone help? Which code should i try to sort them? some facebook api code or php code. if php then maybe you have some tips how to do this.Cheers!
Try This to make it work like you mentioned:
$friends = json_decode($facebook->api('/me/friends?fields=birthday'));
$friends_birth = array();
foreach($friends->data as $value){
if(isset($value->birthday->)){
$dt = split("/",$value->birthday);
$friends_birth[$value->id] = mktime(0,0,0,$dt[0],$dt[1], date("y"));
}
}
asort($friends_birth);
echo print_r($friends_birth);
This will sort friends in birthday wise... now you can use this data for further logic
i've resolve the problem by myself. quite simple solutions... maybe too simple but works perfect. That's my code. maybe it help someone in future ;)
$fql_n = "SELECT uid, name, birthday_date FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND strlen(birthday_date) != 0 ORDER BY birthday_date";
$parame = array(
'method' => 'fql.query',
'query' => $fql_n,
'callback' => ''
);
$fqlResultt = $facebook->api($parame);
$ile_dat = 0;
$miesiace_slownie = array("01" => "jan", "02" => "feb", "03" => "mar", "04" => "apr", "05" => "may", "06" => "jun", "07" => "jul", "08" => "aug", "09" => "sep", "10" => "oct", "11" => "nov", "12" => "dec");
if($fqlResultt){
foreach($fqlResultt as $ress){
$data = date("m/d");
list($fb_m,$fb_d) = explode("/", $ress['birthday_date']);
$fb_date = $fb_m."/".$fb_d;
if($data<=$fb_date) { ?>
<div class="fb_birthday_fr">
<span class="fb_brt_day"><?php echo $fb_d . ' ' . $miesiace_slownie[$fb_m]; ?></span>
<span class="fb_brt_fr"><?php echo $ress['name']; ?></span>
</div>
<?php
$ile_dat++;
if($ile_dat == 6) break;
}
}
}
$miesiace_slownie is a array that's convert month data from facebook into local language type.
cheers and many thanks ^Love Sharma for given help. Beer for you ;)