Twitter Ruby Gem - get friends names and ids, nothing more - ruby

Is it possible to simply get the people you are following with just an id and full name? I do not need any of the additional data, it's a waste of bandwidth.
Currently the only solution I have is:
twitter_client = Twitter::Client.new
friend_ids = twitter_client.friend_ids['ids']
friends = twitter_client.users(friend_ids).map { |f| {:twitter_id => f.id, :name => f.name} }
is there anyway to just have users returned be an array of ids and full names? better way of doing it than the way depicted above? preferably a way to not filter on the client side.

The users method uses the users/lookup API call. As you can see on the page, the only param available is include_entities. The only other method which helps you find users has the same limitation. So you cannot download only the needed attributes.
The only other thing I'd like to say is that you could directly use the friends variable, I don't see any benefit of running the map on it.

Related

Association Exclude Based on Field

I'm looking for the best Ruby way to accomplish this.
I have a Person that has_many Feeds through Subscriptions. So we can do things like Person.feeds, and it gets all the feeds a person is subscribed to.
Problem is, subscriptions are either authorized or deauthorized. What is the best way to make Person.feeds respect the Authorized status bit on the Subscription model?
So we can do something like Person.feeds.where(:status => authorized).
You can call this with a command like the following:
#person.feeds.joins(:subscription).where(subscriptions: { status: 'authorized' })
N.B. the joins takes the association's format, singular in this case, while where takes the table name, typically pluralised.
What this does in order is:
Loads the feeds belonging to a person
Joins these feeds to their subscription
Queries the subscriptions table to return only the feeds where the subscription is active
To refactor this, I'd include a couple of methods in the relevant models:
# feed.rb
scope :active, -> { joins(:subscription).where(subscriptions: { status: 'authorized' }) }
# person.rb
def active_feeds
feeds.active
end
Then, you can just call #person.active_feeds to get the results you want from anywhere in your code base.
(There's also the added bonus of Feed.active being available anywhere should you wish to display active feeds outside of a user's scope.)
Hope that helps - let me know if you've any questions.

DataMapper use only certain columns

I have a code section like the following:
users = User.all(:fname => "Paul")
This of course results in getting all users called "Paul". Now I only need some of the columns available for each user which leads to replacing the above line by something like this:
users = User.all(:name => "Paul", :fields => [:id, :fname, :lname, :email])
Until now everything works as expected. Unfortunately now I want to work with users but as soon as I use something like users.to_json, also the other columns available will be lazy-loaded even due the fact, that I don't need those. What's the correct or at least a good way to end up with users only containing the attributes for each user that I need?
An intermediate object like suggested in How to stop DataMapper from double query when limiting columns/fields? is not a very good option as I have a lot of places where would need to define at least twice which fields I need and also I would loose the speed improvement gained by loading only the needed data from the DB. In addition such an intermediate object also seems to be quite ugly to build when having multiple rows of the DB selected (=> multiple objects in a collection) instead of just one.
If you usually works with the collection using json I suggest overriding the as_json method in your model:
def as_json(options = nil)
# this example ignores the user's options
super({:only => [:fname]}.merge(options || {}))
end
You are able to find more detailed explanation here http://robots.thoughtbot.com/better-serialization-less-as-json

How can I efficiently pull specific information from JSON

I currently have a public Google calendar that I am successfully pulling JSON data down using Google's API.
I am using HTTParty to convert the JSON to a ruby object.
response = HTTParty.get('http://www.google.com/calendar/feeds/colorado.edu_mdpltf14q21hhg50qb3e139fjg#group.calendar.google.com/public/full?alt=json&orderby=starttime&max-results=15&singleevents=true&sortorder=ascending&futureevents=true')
I want to retrieve many titles, event names, start times, end times ect. I can get these with commands like
response["feed"]["title"["$t"]
for the calendar's title, and
response["feed"]["entry"][0]["title"]["$t"]
for the event's title.
My question is two-fold. One, Is there a simpler way to pull this data? Two, how can I go about pulling multiple events information? I tried:
response.each do |x| response["feed"]["title"]["$t"]
but that spits out a no implicit conversion of string into integer error.
Based on your examples this should do it
response["feed"]["entry"].map {|entry| entry["title"]["$t"] }
response['feed']['entry'] is a simple array of hashes. It is probably best to extract that array to a temporary variable with
entries = response['feed']['entry']
thereafter your code it depends entirely on what you need to achieve. For instance, using the URL that you have provided
puts entries.length
shows
2
And
entries.each do |entry|
puts entry['title']['$t']
end
gives
NEW EVENT
Future EVENT
If we can help you to achieve something specific then please alter your answer or ask for clarification in a comment.

loadByRequestPath() is Overriding Parameter With Current URL Path

I am trying to load a rewrite rule based on a product's URL path.
I am using the loadByRequestPath() method in Mage_Core_Model_Url_Rewrite to accomplish this. However, no matter what I supply this method I get the following result (Check comment in code):
public function loadByRequestPath($path)
{
Zend_Debug::dump($path); // returns the path to my module
$this->setId(null);
$this->_getResource()->loadByRequestPath($this, $path);
$this->_afterLoad();
$this->setOrigData();
$this->_hasDataChanges = false;
return $this;
}
Here is my module code:
$productRewrite = Mage::getModel('core/url_rewrite') ->loadByRequestPath($product->getUrlPath());
Oddly, I get this back:
Array ( [0] => rewrites/getProductRewrites
[1] => rewrites/getProductRewrites/ )
Array ( [0] => 01003-product-name )
So loadByRequestPath() is getting called twice for whatever reason. $productRewrite still returns an empty object.
I have verified that $product->getUrlPath() returns the correct path. (As seen in the second array)
I am on Magento 1.6.1.
Your question is still a little unclear, so this answer might not address the specific problem you're seeing.
Magento's core team hasn't done a great job of communicating these sorts of things over the years, but loadByRequestPath is one of those methods that's best thought of as a "private api". Not in the OOP sense, but in the "this is a method used to implement core system functionality, and probably won't work like you think it should work, so use at your own risk".
The PHP code you're trying to use
$productRewrite = Mage::getModel('core/url_rewrite') ->loadByRequestPath($product->getUrlPath());
won't work with a default installation of Magento because the rewrite object doesn't have a store ID set. Trying something like this should work. (assuming the sample data, with an installed store object that has an ID of "1" and that the product in question exists in that store)
$productRewrite = Mage::getModel('core/url_rewrite');
$productRewrite->setStoreId(1);
$productRewrite->loadByRequestPath($product->getUrlPath());
The loadByRequestPath method assumes that a rewrite already has a store ID set, as it's part of Magento's larger dispatching process. (self-link to article describing the role of rewrites in Magento's routing system)
All that said, the problem you're describing is somewhat confusing. You say that
Zend_Debug::dump($path);
returns
an array that contains the path to my module
While I'm sure you know what the phrase "path to my module" means, it's a meaningless term in the larger magento universe. Being more specific about the literal value will help people understand what you mean.
Additionally, you also say
I have verified that $product->getUrlPath() returns the correct path.
but you're not clear on the value of "the correct path".
My guess would be the path you're seeing in Zend_Debug::dump is the call that's coming through as a part of the standard dispatch and not your later call using $product->getUrlPath(). However, the lack of clarity in your question makes that hard to tell.
If setting the store ID doesn't get you what you want, update your question with a full explanation of how you're running your code, and what you see displayed. With that information more people will be able to help you.

CakePHP, organize site structure around groups

So, I'm not quite sure how I should structure this in CakePHP to work correctly in the proper MVC form.
Let's, for argument sake, say I have the following data structure which are related in various ways:
Team
Task
Equipment
This is generally how sites are and is quite easy to structure and make in Cake. For example, I would have the a model, controller and view for each item set.
My problem (and I'm sure countless others have had it and already solved it) is that I have a level above the item sets. So, for example:
Department
Team
Task
Equipment
Department
Team
Task
Equipment
Department
Team
Task
Equipment
In my site, I need the ability for someone to view the site at an individual group level as well as move to view it all together (ie, ignore the groups).
So, I have models, views and controls for Depart, Team, Task and Equipment.
How do I structure my site so that from the Department view, someone can select a Department then move around the site to the different views for Team/Task/Equipment showing only those that belong to that particular Department.
In this same format, is there a way to also move around ignoring the department associations?
Hopefully the following example URLs clarifies anything that was unclear:
// View items while disregarding which group-set record they belong to
http://www.example.com/Team/action/id
http://www.example.com/Task/action/id
http://www.example.com/Equipment/action/id
http://www.example.com/Departments
// View items as if only those associated with the selected group-set record exist
http://www.example.com/Department/HR/Team/action/id
http://www.example.com/Department/HR/Task/action/id
http://www.example.com/Department/HR/Equipment/action/id
Can I get the controllers to function in this manner? Is there someone to read so I can figure this out?
Thanks to those that read all this :)
I think I know what you're trying to do. Correct me if I'm wrong:
I built a project manager for myself in which I wanted the URLs to be more logical, so instead of using something like
http://domain.com/project/milestones/add/MyProjectName I could use
http://domain.com/project/MyProjectName/milestones/add
I added a custom route to the end (!important) of my routes so that it catches anything that's not already a route and treats it as a "variable route".
Router::connect('/project/:project/:controller/:action/*', array(), array('project' => '[a-zA-Z0-9\-]+'));
Whatever route you put means that you can't already (or ever) have a controller by that name, for that reason I consider it a good practice to use a singular word instead of a plural. (I have a Projects Controller, so I use "project" to avoid conflicting with it.)
Now, to access the :project parameter anywhere in my app, I use this function in my AppController:
function __currentProject(){
// Finding the current Project's Info
if(isset($this->params['project'])){
App::import('Model', 'Project');
$projectNames = new Project;
$projectNames->contain();
$projectInfo = $projectNames->find('first', array('conditions' => array('Project.slug' => $this->params['project'])));
$project_id = $projectInfo['Project']['id'];
$this->set('project_name_for_layout', $projectInfo['Project']['name']);
return $project_id;
}
}
And I utilize it in my other controllers:
function overview(){
$this->layout = 'project';
// Getting currentProject id from App Controller
$project_id = parent::__currentProject();
// Finding out what time it is and performing queries based on time.
$nowStamp = time();
$nowDate = date('Y-m-d H:i:s' , $nowStamp);
$twoWeeksFromNow = $nowDate + 1209600;
$lateMilestones = $this->Project->Milestone->find('all', array('conditions'=>array('Milestone.project_id' => $project_id, 'Milestone.complete'=> 0, 'Milestone.duedate <'=> $nowDate)));
$this->set(compact('lateMilestones'));
$currentProject = $this->Project->find('all', array('conditions'=>array('Project.slug' => $this->params['project'])));
$this->set(compact('currentProject'));
}
For your project you can try using a route like this at the end of your routes.php file:
Router::connect('/:groupname/:controller/:action/*', array(), array('groupname' => '[a-zA-Z0-9\-]+'));
// Notice I removed "/project" from the beginning. If you put the :groupname first, as I've done in the last example, then you only have one option for these custom url routes.
Then modify the other code to your needs.
If this is a public site, you may want to consider using named variables. This will allow you to define the group on the URL still, but without additional functionality requirements.
http://example.com/team/group:hr
http://example.com/team/action/group:hr/other:var
It may require custom routes too... but it should do the job.
http://book.cakephp.org/view/541/Named-parameters
http://book.cakephp.org/view/542/Defining-Routes
SESSIONS
Since web is stateless, you will need to use sessions (or cookies). The question you will need to ask yourself is how to reflect the selection (or not) of a specific department. It could be as simple as putting a drop down selection in the upper right that reflects ALL, HR, Sales, etc. When the drop down changes, it will set (or clear) the Group session variable.
As for the functionality in the controllers, you just check for the Session. If it is there, you limit the data by the select group. So you would use the same URLs, but the controller or model would manage how the data gets displayed.
// for all functionality use:
http://www.example.com/Team/action/id
http://www.example.com/Task/action/id
http://www.example.com/Equipment/action/id
You don't change the URL to accommodate for the functionality. That would be like using a different URL for every USER wanting to see their ADDRESS, PHONE NUMBER, or BILLING INFO. Where USER would be the group and ADDRESS, PHONE NUMBER< and BILLING INFO would be the item sets.
WITHOUT SESSIONS
The other option would be to put the Group filter on each page. So for example on Team/index view you would have a group drop down to filter the data. It would accomplish the same thing without having to set and clear session variables.
The conclusion is and the key thing to remember is that the functionality does not change nor does the URLs. The only thing that changes is that you will be working with filtered data sets.
Does that make sense?

Resources