Haml alphabetizes attributes. Can you override that? [duplicate] - haml

If I create an XML element in HAML:
%tag{:b => "b", :a => "a"}
I get this output:
<tag a="a" b="b"/>
Is it possible to keep the ordering of the attributes in HAML?
I need this for a client-side code to display values in certain order and don't want to pass extra information on the client just to maintain ordering.

It's not possible with HAML because it's a hash.

Related

Detect hash tag and srip the # for clean url

consider the string
$tring = "e.g. i want to #sleep."
Am able to check for hash tags using
echo preg_replace('/(#\w+)/','\1',$tring']);
What i want to do is send the tag without the hash in front i.e. #sleep instead of #sleep
You can modify your regex slightly to make this work properly.
echo preg_replace('/(#)(\w+)/i', '\1\2', $tring);
This creates two groupings, instead of the one that you had. Only the second group, the word, is used in the URL link. Both are used in the display test.
Examples of how this will work
e.g. i want to #sleep. => e.g. i want to #sleep.
this is a #cow => this is a #cow
the #duck is #sleeping => the #duck is #sleeping
#regex are #awesome #fun => #regex are #awesome #fun
As you can see, this handles multiple tags in the string as well.

Yii CHtml::dropDownList. Same value under different labels

CHtml::dropDownList('name','select',$listData,$htmlOptions);
Everything is OK until I faced one issue. I've got an array, which looks like this:
array(
array('ua', 'Ukraine', '380'),
array('ru', 'Russia', '7'),
...
array('kz', 'Kazakhstan', '7'),
);
$listData is an array of (value=>label). First I walked through array and made (code=>country) array as $listData. But I found that different countries may have the same code. I can use first "two letter geo" as key, and $listData will be an unique array.
And what if I need the same value but under different labels?
It seems that the only Yii solution is to concatenate labels under one key(value).
Or use pure html and echo each option separate.
I think the sensible way to do this is with a new model, with a new id (INTEGER PRIMARY KEY AUTOINCREMENT), and hold the data in separate fields (country, geo, code.)
Create your listdata to be an array using only the new id and the country so the array looks something like this:
array( 0=>'Ukraine', 1=>'Russia', 2=>'Kazakhstan' );
This way you will only send the id, and figure out the data (geo, code, country) on the receiver side.
But I must ask about this:
It seems that the only Yii solution is to concatenate labels under one key(value).
How do you want a option-tag to look like exactly?
<option value="ua" code="380">Ukraine</option> // Like this?
Then you should set htmlOptions similar to this:
array(
'ua'=>array('code'=>'380'),
'ru'=>array('code'=>'7'),
...
);

Sorting Strings in Rails using Order

I Have a model "Msg" and it has a content as a string and a username as a string as well
at the moment all my Msgs have their content Lorem Ipsumed and I'd like to sort them out
I'm trying to do something like
Msg.all(:order => "content DESC")
but it will not sort the strings for me..
Is there anyway to sort the strings in one line to get all of the Msgs (or the actual strings)
Thanks
Im not sure to understand the question.
Msg.all(:order => "content DESC")
retrieves all messages ordered by its content. Consequently, mapping its content attributes returns all the strings properly sorted
Msg.all(:order => "content DESC").map(&:content)

Rails 3 selecting only values

In rails 3, I would like to do the following:
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id")
This works, but i get the following from the DB:
[{"some_other_connection_id":254},{"some_other_connection_id":315}]
Now, those id-s are the ones I need, but I am uncapable of making a query that only gives me the ids. I do not want to have to itterate over the resulst, only to get those numbers out. Are there any way for me to do this with something like :
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id").values()
Or something of that nautre?
I have been trying with the ".select_values()" found at Git-hub, but it only returns "some_other_connection_id".
I am not an expert in rails, so this info might be helpful also:
The "SomeModel" is a connecting table, for a many-to-many relation in one of my other models. So, accually what I am trying to do is to, from the array of IDs, get all the entries from the other side of the connection. Basicly I have the source ids, and i want to get the data from the models with all the target ids. If there is a magic way of getting these without me having to do all the sql myself (with some help from active record) it would be really nice!
Thanks :)
Try pluck method
SomeModel.where(:some => condition).pluck("some_field")
it works like
SomeModel.where(:some => condition).select("some_field").map(&:some_field)
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id").map &:some_other_connection_id
This is essentially a shorthand for:
results = SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id")
results.map {|row| row.some_other_connection_id}
Look at Array#map for details on map method.
Beware that there is no lazy loading here, as it iterates over the results, but it shouldn't be a problem, unless you want to add more constructs to you query or retrieve some associated objects(which should not be the case as you haven't got the ids for loading the associated objects).

Rails 3 ActiveRecord query using both SQL IN and SQL OR operators

I'm writing a Rails 3 ActiveRecord query using the "where" syntax, that uses both the SQL IN and the SQL OR operator and can't figure out how to use both of them together.
This code works (in my User model):
Question.where(:user_id => self.friends.ids)
#note: self.friends.ids returns an array of integers
but this code
Question.where(:user_id => self.friends.ids OR :target => self.friends.usernames)
returns this error
syntax error, unexpected tCONSTANT, expecting ')'
...user_id => self.friends.ids OR :target => self.friends.usern...
Any idea how to write this in Rails, or just what the raw SQL query should be?
You don't need to use raw SQL, just provide the pattern as a string, and add named parameters:
Question.where('user_id in (:ids) or target in (:usernames)',
:ids => self.friends.ids, :usernames => self.friends.usernames)
Or positional parameters:
Question.where('user_id in (?) or target in (?)',
self.friends.ids, self.friends.usernames)
You can also use the excellent Squeel gem, as #erroric pointed out on his answer (the my { } block is only needed if you need access to self or instance variables):
Question.where { user_id.in(my { self.friends.ids }) |
target.in(my { self.friends.usernames }) }
Though Rails 3 AR doesn't give you an or operator you can still achieve the same result without going all the way down to SQL and use Arel directly. By that I mean that you can do it like this:
t = Question.arel_table
Question.where(t[:user_id].in(self.friends.ids).or(t[:username].in(self.friends.usernames)))
Some might say it ain't so pretty, some might say it's pretty simply because it includes no SQL. Anyhow it most certainly could be prettier and there's a gem for it too: MetaWhere
For more info see this railscast: http://railscasts.com/episodes/215-advanced-queries-in-rails-3
and MetaWhere site: http://metautonomo.us/projects/metawhere/
UPDATE: Later Ryan Bates has made another railscast about metawhere and metasearch: http://railscasts.com/episodes/251-metawhere-metasearch
Later though Metawhere (and search) have become more or less legacy gems. I.e. they don't even work with Rails 3.1. The author felt they (Metawhere and search) needed drastic rewrite. So much that he actually went for a new gem all together. The successor of Metawhere is Squeel. Read more about the authors announcement here:
http://erniemiller.org/2011/08/31/rails-3-1-and-the-future-of-metawhere-and-metasearch/
and check out the project home page:
http://erniemiller.org/projects/squeel/
"Metasearch 2.0" is called Ransack and you can read something about it from here:
http://erniemiller.org/2011/04/01/ransack-the-library-formerly-known-as-metasearch-2-0/
Alternatively, you could use Squeel. To my eyes, it is simpler. You can accomplish both the IN (>>) and OR (|) operations using the following syntax:
Question.where{(:user_id >> my{friends.id}) | (:target >> my{friends.usernames})}
I generally wrap my conditions in (...) to ensure the appropriate order of operation - both the INs happen before the OR.
The my{...} block executes methods from the self context as defined before the Squeel call - in this case Question. Inside of the Squeel block, self refers to a Squeel object and not the Question object (see the Squeel Readme for more). You get around this by using the my{...} wrapper to restore the original context.
raw SQL
SELECT *
FROM table
WHERE user_id in (LIST OF friend.ids) OR target in (LIST OF friends.usernames)
with each list comma separate. I don't know the Rails ActiveRecord stuff that well. For AND you would just put a comma between those two conditions, but idk about OR